如何动态更改片段的类

时间:2011-09-15 13:17:38

标签: android android-layout android-fragments

您好我有一个包含两个片段的linearLayout,我在此布局中添加了代码选项卡。我想要的是当我点击tab1时可以从指定的类中填充自己的片段,但是在tab2中我想将这个类更改为另一个类。谢谢

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/frags">

   <fragment class="com.tugce.MitsActionBar.DoktorlarFragment"
            android:id="@+id/frag_title"
            android:visibility="gone"
            android:layout_marginTop="?android:attr/actionBarSize"
            android:layout_width="@dimen/titles_size"
            android:layout_height="match_parent" /> 

    <fragment class="com.tugce.MitsActionBar.ContentFragment"
            android:id="@+id/frag_content"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

2 个答案:

答案 0 :(得分:24)

将xml布局中的<fragment/>更改为<FrameLayout/>

<FrameLayout
        android:id="@+id/frag_title"
        android:visibility="gone"
        android:layout_marginTop="?android:attr/actionBarSize"
        android:layout_width="@dimen/titles_size"
        android:layout_height="match_parent" /> 

<FrameLayout
        android:id="@+id/frag_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

以编程方式添加片段:

FragmentManager fragmentManager = getFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.replace(R.id.frag_content, fragment);
fragmentTransaction.commit();

但首先阅读this

答案 1 :(得分:3)

调用片段的最短版本

getFragmentManager().beginTransaction().replace(R.id.splash_container, new ExampleFragment()).addToBackStack(null).commit();
如果要将片段保存在堆栈上,

addToBackStack(null)是可选的。

相关问题