当你的应用需要支持很多种屏幕尺寸,你可以在不同的布局配置中重用你的Fragment组件在可用的屏幕尺寸上优化用户体验。
例如,在手持设备中一次只显示一个Fragment可能是一个合适的选择,当然在Pad设备中将两个Fragment拼在一起来填满更大尺寸的屏幕,同时为用户显示更多的信息。
在上图中,两个Fragment,配合不同的配置显示在不同尺寸的屏幕上的效果。
FragmentManager类提供了运行时在Activity上添加,移除或者替换Fragment的方法,从而可以制造出动态的体验。
在运行的Activity中添加一个Fragment
你可以在运行中的Activity中添加Fragment,如果你想在Activity的生命周期中改变Fragment。
FragmentManager类提供了运行时在Activity上添加,移除或者替换Fragment的方法,从而可以制造出动态的体验。
如果你的Activity允许Fragment被移除和替换,你需要在Activity的onCreate方法中添加初始化的Fragment(s)。
一个处理Fragment的重要原则,Fragment必须有一个在布局中有一个让其寄存的View容器,特别是对那些运行时的Fragment。
以下是一个布局文件,每次显示一个Fragment。为了用一个Fragment替换另外一个,Activity的布局文件包含一个空的FrameLayout,作为Fragment容器使用。
- res/layout/news_articles.xml:
- <FrameLayoutxmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/fragment_container"
- android:layout_width="match_parent"
- android:layout_height="match_parent" />
.
在Activity当中,利用getSupportFragmentManager()获取一个FragmentManager,以下是代码示例:
- import android.os.Bundle;
- import android.support.v4.app.FragmentActivity;
- public class MainActivity extends FragmentActivity {
- @Override
- public voidonCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.news_articles);
- // Checkthat the activity is using the layout version with
- // thefragment_container FrameLayout
- if(findViewById(R.id.fragment_container) != null) {
- //However, if we're being restored from a previous state,
- // thenwe don't need to do anything and should return or else
- // wecould end up with overlapping fragments.
- if(savedInstanceState != null) {
- return;
- }
- // Create an instance of ExampleFragment
- HeadlinesFragment firstFragment = new HeadlinesFragment();
- // Incase this activity was started with special instructions from an Intent,
- // passthe Intent's extras to the fragment as arguments
- firstFragment.setArguments(getIntent().getExtras());
- // Addthe fragment to the 'fragment_container' FrameLayout
- getSupportFragmentManager().beginTransaction()
- .add(R.id.fragment_container,firstFragment).commit();
- }
- }
- }
Fragment替换
替换Fragment的流程和添加的流程类似,只不过需要利用replace方法替换add方法。
需要记住的是,当你是Fragment切换的时候,例如替换或者一处,最好让用户拥有返回或者撤销的机会
当你允许用户返回或者撤销Fragment操作的时候,你必须在调用FragmentTransaction之前调用addToBackStack。
以下是一个示例:
- // Create fragment and give it an argument specifying thearticle 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 viewwith this fragment,
- // and add the transaction to the back stack so the usercan navigate back
- transaction.replace(R.id.fragment_container,newFragment);
- transaction.addToBackStack(null);
- // Commit the transaction
- transaction.commit();