当Fragment指定自己的布局后,在同一个Activity中,就能与其它的Fragment相互组合,产生出一种布局上的配置,这种配置能随着手机屏幕的大小而自动调整,(比如,在小屏手机上显示两个Fragment,在大屏手机上能显示两个 Fragment)。Fragment就像是一个嵌套的Activity,有自己的布局,能管理自己的生命周期。
一、创建一个Fragment
二、生成灵活的UI你可以把Fragment想象成Activity的一部分,拥有自己的生命周期循环,接收输入事件,并且能在Activity运行时,进行动态添加和删除。就像子Activity,可以在不同的Activity中重用。
1.1、创建Fragment类
继承Fragment,重写关键的生命周期方法。与创建Activity的套路有点像。与Activity不同的是,你必须使用onCreateView()方法来定义Fragment的布局, 实际上,这个方法是能让Fragment跑起来的唯一方法。public class ArticleFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.article_view, container, false); } }Fragment也需要实现一些自己的生命周期回调方法来管理一些状态,包括从Activity中添加或者删除时,或者Activity在各个生命周期之前转换时,比如:如果Activity运行了onPause(),那么在它之中的各个Fragment都会自动进行各自的onPause()回调。
1.2、用XML向Activity中添加Fragment
Fragment是可以重用的,是UI模块的组成部分,所有的Fragment类的实例都必须有一个和它关联的作为Parent的FragmentActivity,通过把各个Fragment写入到Activity的布局XML文件中,就可以实现这个关联。FragmentActivity是低版本支持库中提供一个管理低版本Fragment的特殊Activity,在3.0以上版本中,还是使用标准的Activity。以下是在大屏幕的布局文件中,添加两个Fragmentres/layout-large/news_articles.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent"> <fragment android:name="com.example.android.fragments.HeadlinesFragment" android:id="@+id/headlines_fragment" android:layout_weight="1" android:layout_width="0dp" android:layout_height="match_parent" /> <fragment android:name="com.example.android.fragments.ArticleFragment" android:id="@+id/article_fragment" android:layout_weight="2" android:layout_width="0dp" android:layout_height="match_parent" /> </LinearLayout>然后把布局文件应用到Activityimport 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); } }如果你在使用v7 appcompat library,就要把FragmentActivity改为ActionBarActivity,它是FragmentActivity的一个子类。
FragmentManager类提供动态添加和删除Fragment的方法。
2.1、动态添加一个Fragment
除了能用以上的方法通过XML的方式添加Fragment以外,还可以在Activity运行时添加,这了实现添加、删除、替换Fragment,就得通过FragmentManager类得到FragmentTransaction,它提供对Fragment操作的API。如果Activity允许对Fragment进行添加和替换,那么在Activity 的 onCreate()方法中就要生成一个初始的Fragment。对于处理Fragment,特别是动态添加的Fragment来说,一个重要的规则是,必须要提供一个View容器来装载Fragment的布局。
下面的Layout文件是上面Layout文件的一个副本,它表示一次只显示一个Fragment,注意它文件名与上边的也是一样,但是少了Large,说明此Layout是在屏幕小于large时加载的,另外,为了实现Fragment的替换,里面定义了一个空的Fragment来充当Fragment的容器。
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" />在Activity中,调用getSupportFragmentManager()得到FragmentManager,然后再调用beginTransaction()来创建FragmentTransaction,最后调用add()方法添加一个Fragment。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(); } } }
2.2、替换Fragment
在做Fragment删除或者替换操作时,用户有时候会按返回键回到上一个状态,要实现这个效果,就要在FragmentTransaction提交前调用addToBackStack()方法。
当把Fragment移除或者替换后添加到后退栈中时,Fragment处于stop状态,用户返回后又会恢复,如果仅仅是移除或者替换而不加入到后退栈中,Fragment将会被销毁。// 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();addToBackStack()方法中要传入一个String类型的参数,为Transation指定唯一名称,一般是没用的,除非要用到FragmentManager.BackStackEntry API,实现Fragment的高级操作。
三、与其它Fragment通信
所有Fragment间的通信都是通过他们关联的Activity完成,Fragment之间是不能通信的。
3.1、定义一个接口
为了实现Fragment与Activity之间的通信,在Fragment类中定义一个接口和相应的回调方法,让Activity实现这个接口,并实现回调方法,public class HeadlinesFragment extends ListFragment { OnHeadlineSelectedListener mCallback; // Container Activity must implement this interface public interface OnHeadlineSelectedListener { public void onArticleSelected(int position); } @Override public void onAttach(Activity activity) { super.onAttach(activity); // This makes sure that the container activity has implemented // the callback interface. If not, it throws an exception try { mCallback = (OnHeadlineSelectedListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnHeadlineSelectedListener"); } } ... }@Override public void onListItemClick(ListView l, View v, int position, long id) { // Send the event to the host activity mCallback.onArticleSelected(position); }3.2、实现这个接口public static class MainActivity extends Activity implements HeadlinesFragment.OnHeadlineSelectedListener{ ... public void onArticleSelected(int position) { // The user selected the headline of an article from the HeadlinesFragment // Do something here to display that article } }3.3、向Fragment传递消息
Activity可以通过findFragmentById()方法捕获Fragment实例,然后直接调用Fragment的公共方法,这样就完成了消息的传送。
还用上面的例子,当 HeadlinesFragment 通过Item的点击事件要实现对应的Item主体的显示,向Activity发出点击的Position信息后,Activity再获取 ArticleFragment的实例,把position通过Bundle的方式传递给它,来显示文章正文。
public static class MainActivity extends Activity implements HeadlinesFragment.OnHeadlineSelectedListener{ ... public void onArticleSelected(int position) { // The user selected the headline of an article from the HeadlinesFragment // Do something here to display that article ArticleFragment articleFrag = (ArticleFragment) getSupportFragmentManager().findFragmentById(R.id.article_fragment); if (articleFrag != null) { // If article frag is available, we're in two-pane layout... // Call a method in the ArticleFragment to update its content articleFrag.updateArticleView(position); } else { // Otherwise, we're in the one-pane layout and must swap frags... // Create fragment and give it an argument for the selected article 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(); } } }