TaZaiia 2015-08-04 09:17 采纳率: 0%
浏览 7434
已采纳

怎么从activity跳转到fragment中,

能发写个代码段吗,我看看。。
好像这不叫跳转。。怎么在activity托管fragment在利用fragment呢。。。
能发写个代码段吗,我看看。。

  • 写回答

4条回答 默认 最新

  • fanst_ 2015-08-04 11:03
    关注

    Fragment是片段,和Activity不是对等的关系,可以理解是整个Activity页面的一部分,我刚开始学Android,刚写好的Fragment使用例子。其实简单讲需要四个部分:1.Activity的布局(xml)定义,里面要定义Fragment的容器 2.Fragment自身的布局定义 3.Fragment实现类 4.Activity的onCreate中,构造Fragment对象,add到对应的容器中。

    关键代码如下:
    Activity的onCreate():
    protected void onCreate(Bundle savedInstanceState)
    {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tab_home_page);
    fm = this.getFragmentManager();
    // 例子中是四个Tab页,因此用了四个不同的Fragment类
    frags[0] = new MyFragment1();
    frags[1] = new MyFragment2();
    frags[2] = new MyFragment3();
    frags[3] = new MyFragment4();;
    FragmentTransaction ft = fm.beginTransaction();
    ft.add(R.id.content, frags[0]); // add方法第一个参数是容器的ID,即下面xml中定义的FrameLayout
    ft.add(R.id.content, frags[1]).hide(frags[1]);
    ft.add(R.id.content, frags[2]).hide(frags[2]);
    ft.add(R.id.content, frags[3]).hide(frags[3]);
    ft.commit();

    Activity的layout中包含一个FrameLayout(我的是同一个区域有多个Fragment,类似Tab页效果,因此用了FrameLayout作为Fragment的容器):
    注意:如果像上面用代码中new Fragment实例的方式的话,layout中不需要放Fragment节点(xml定义和代码构造Fragment对象是两种方式),仅需要定义容器节点,我下面就注释掉了
    android:id="@+id/content"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1" >
    <!--

    android:id="@+id/fragment1"
    android:name="com.example.fst.fragment.Fragment1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

        <fragment
            android:id="@+id/fragment2"
            android:name="com.example.fst.fragment.Fragment2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" >
        </fragment>
        -->
    </FrameLayout>
    

    Fragment的类:
    public class Fragment1 extends Fragment
    {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View rootView = inflater.inflate(R.layout.fragment1, container, false);
    
        return rootView;
    }
    

    }

    Fragment的layout文件:
    <?xml version="1.0" encoding="utf-8"?>
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/mytv_text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is MyTV" />
    

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站