2011-09-15 108 views
6

嗨,我有一个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" /> 

回答

24

变化<fragment/>在xml配置<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

谢谢您的回答,我只是用我的片段= DoktorlarFragment取代的FrameLayout ()没有错误,屏幕上没有任何内容你知道为什么吗? – tugce

3

最短调用一个片段

getFragmentManager().beginTransaction().replace(R.id.splash_container, new ExampleFragment()).addToBackStack(null).commit(); 

addToBackStack(null)是可选的,如果你想节省栈或没有该片段的版本..