当设计应用程序以支持各种屏幕尺寸时,您可以在不同的布局结构上重用片段来优化用户体验。
例如,在手持设备上单窗格的用户界面一次只能显示一个片段,相反,在平板或者具有更宽屏幕尺寸上你需要设置并排的片段以给用户展现更多的信息
为一个运行时活动添加一个片段
不同于在布局文件使用使用<element>元素来定义片段,我们可以在活动运行时动态添加片段。如果您计划在活动的生命周期内改变片段,那么这是必要的。
为了执行一个添加或删除片段的事务,你必须使用FragmentManager创建FragmentTransaction,FragmentTransaction可以提供API来添加,删除,替换以及其他的片段事务。
如果你的活动允许片段移除和替换,你必须在活动的onCreate()方法中添加初始片段。
一个重要的规则是,你处理的片段,尤其是那些在运行时候加入的片段必须在布局文件中拥有容器视图,让这些片段驻留。
res/layout/news_articles.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/fragment_container" android:layout_width="match_parent" android:layout_height="match_parent" />
您可以使用同一个FragmentTransaction执行多个片段的事务。当你准备进行更改,则必须调用commit()。
如下图的例子,就是增加一个前面布局的片段
import android.os.Bundle; import android.support.v4.app.FragmentActivity; public class MainActivity extends FragmentActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.news_articles); // Check that the activity is using the layout version with // the fragment_container FrameLayout if (findViewById(R.id.fragment_container) != null) { // However, if we're being restored from a previous state, // then we don't need to do anything and should return or else // we could end up with overlapping fragments. if (savedInstanceState != null) { return; } // Create a new Fragment to be placed in the activity layout HeadlinesFragment firstFragment = new HeadlinesFragment(); // In case this activity was started with special instructions from an // Intent, pass the Intent's extras to the fragment as arguments firstFragment.setArguments(getIntent().getExtras()); // Add the fragment to the 'fragment_container' FrameLayout getSupportFragmentManager().beginTransaction() .add(R.id.fragment_container, firstFragment).commit(); } } }
用另一个片段替换
替换一个片段的过程和增加片段过程类似,但是使用replace()方法而不是add()方法。
请记住,当你执行片段事务,如替换或删除一个,它往往允许用户往后导航或者撤销改变。为了让用户能够通过片段事务向后导航,在你提交FragmentTransaction之前你必须调用addToBackStack()。
注意,当您移除或者替换片段并且讲事务添加到后退栈中,被去除的片段被停止(但是没有被破坏)。如果用户导航回原片段,它被重新启动。如果不将事物添加到后退栈中,当移除或者替换时该片段被破坏。
另外一个例子
// Create fragment and give it an argument specifying the article it should show ArticleFragment newFragment = new ArticleFragment(); Bundle args = new Bundle(); args.putInt(ArticleFragment.ARG_POSITION, position); newFragment.setArguments(args); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); // Replace whatever is in the fragment_container view with this fragment, // and add the transaction to the back stack so the user can navigate back transaction.replace(R.id.fragment_container, newFragment); transaction.addToBackStack(null); // Commit the transaction transaction.commit();