在片段中替换或创建新视图?

时间:2012-06-05 09:20:22

标签: android android-listview android-fragments

我构建了一个活动,它从rss文件中获取数据并在ListFragment上显示它们;这是我在布局文件中定义它的方式:

        <fragment
        android:id="@+id/news_list_fragment"
        android:name="com.thecoffeedrinker.theforcereader.NewsListFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/header_layout" />

可能没有可用的连接;在这种情况下,我希望应用程序显示一个布局,以警告用户它,在列表的相同布局区域中显示。实现这一目标最好的办法是什么?我应该创建一个“断开连接的片段”类并用同一活动的列表替换实例吗?我应该在List Fragment类中加载此布局吗?我试图替换它,但当我恢复活动时它会崩溃......为什么会这样?谢谢你的回复。

1 个答案:

答案 0 :(得分:0)

将一个片段替换为另一个片段

Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();

添加新片段

ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();