【问题标题】:how to change fragment's class dynamically如何动态更改片段的类
【发布时间】:2011-09-15 13:17:38
【问题描述】:

您好,我有一个包含两个片段的线性布局,我在此布局中添加了带有代码的选项卡。我想要的是当我单击 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" />

【问题讨论】:

    标签: android android-layout android-fragments


    【解决方案1】:

    将 xml 布局中的 &lt;fragment/&gt; 更改为 &lt;FrameLayout/&gt;

    <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

    【讨论】:

    • 感谢您的回答我只是将 frameLayout 替换为我的片段 = DoktorlarFragment() 没有错误,屏幕上没有任何内容您知道为什么吗?
    【解决方案2】:

    调用片段的最短版本

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

    addToBackStack(null) 是可选的,如果你想将片段保存在堆栈上..

    【讨论】:

      猜你喜欢
      • 2012-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多