android – 如何动态更改片段的类

前端之家收集整理的这篇文章主要介绍了android – 如何动态更改片段的类前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
嗨我有一个包含两个片段的linearLayout,我在这个布局中添加代码选项卡.我想要的是当我点击tab1时可以从指定的类中填充自己的片段,但是在tab2中我想将这个类更改为另一个类.谢谢
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. android:orientation="horizontal"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:id="@+id/frags">
  6.  
  7. <fragment class="com.tugce.MitsActionBar.DoktorlarFragment"
  8. android:id="@+id/frag_title"
  9. android:visibility="gone"
  10. android:layout_marginTop="?android:attr/actionBarSize"
  11. android:layout_width="@dimen/titles_size"
  12. android:layout_height="match_parent" />
  13.  
  14. <fragment class="com.tugce.MitsActionBar.ContentFragment"
  15. android:id="@+id/frag_content"
  16. android:layout_width="match_parent"
  17. android:layout_height="match_parent" />

解决方法

更改< fragment />在xml布局中< FrameLayout />
  1. <FrameLayout
  2. android:id="@+id/frag_title"
  3. android:visibility="gone"
  4. android:layout_marginTop="?android:attr/actionBarSize"
  5. android:layout_width="@dimen/titles_size"
  6. android:layout_height="match_parent" />
  7.  
  8. <FrameLayout
  9. android:id="@+id/frag_content"
  10. android:layout_width="match_parent"
  11. android:layout_height="match_parent" />

并以编程方式添加片段:

  1. FragmentManager fragmentManager = getFragmentManager()
  2. FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
  3.  
  4. ExampleFragment fragment = new ExampleFragment();
  5. fragmentTransaction.replace(R.id.frag_content,fragment);
  6. fragmentTransaction.commit();

但最初阅读this.

猜你在找的Android相关文章