【Android應用開發技術:應用組件】Fragment使用方法,androidfragment
作者:郭孝星
微博:郭孝星的新浪微博
郵箱:allenwells@163.com
部落格:http://blog.csdn.net/allenwells
Github:https://github.com/AllenWells
一 Fragment管理與事務
Activity通過FragmentManager管理Fragment,FragmentManager可以完成以下功能:
- 調用findFragmentById()或findFragmentByTag()方法來擷取指定的Fragment。在XML檔案中定義Fragment時可以通過android:id或android:tag來標識Fragment。
- 調用popBackStack()方法將Fragment從後台棧中彈出,類比使用者的back鍵。
- 調用addOnBackStackChangeListener()註冊一個監聽器,用來監聽後台棧的變化。
在學習如何建立Fragment之前,我們先來看一下Fragment的繼承體系,如所示:
Fragment繼承體系類圖Visio源檔案下載
建立一個Fragment只需要繼承Fragment類,然後在相應的生命週期方法中寫入商務邏輯。我們在定義一個Fragment時,最常重寫的方法就是onCreateView(),如下所示:
import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.ViewGroup;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); }}
1.1 添加Fragment1.1.1 靜態添加
所謂靜態添加就是在布局檔案總使用元素,元素的android:name屬性指定了實現Fragment的類。這種使用XML布局檔案將Fragment靜態添加到Activity的方法,Fragment是不能被動態移除的。如果想實現Fragment的動態切入和切出,那麼就需要在Activity啟動後,再把Fragment添加到Activity。
舉例
定義一個res/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>
將布局檔案添加到Activity中
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); }}
1.1.2 動態添加
在Java代碼中通過FragmentTransaction對象的add()方法來添加Fragment。Activity的getFragmentManager()方法可返回FragmentManager對象,FragmentManager對象的beginTransaction()方法即可開啟並返回FragmentTransaction對象。
舉例
定義一個res/layout_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" />
1.2 替換Fragment
替換Fragment的過程與添加的過程非常相似,是需要把add()方法替換為replace()方法即可。
注意:當我們執行Fragment事務的時候,比如替換,我們需要適當的讓使用者可以向後導航和撤銷這次操作,為了能夠讓使用者向後導航Fragment事務,我們需要在FragmentTransaction提交前調用addToBackStack()方法。addToBackStack()方法提供了一個可選的String參數為事務指定了一個唯一的名字。這個名字不是必須的,除非 我們打算用FragmentManager.BackStackEntry APIs來進行一些進階的Fragment操作。
當我們移除或者替換一個Fragment並把它放入返回棧中時,被移除的fragment的生命週期是stopped,而不是destoryed。當使用者返回重新恢複這個Fragment,它的生命週期是restarts。如果我們沒把Fragment放入返回棧中,那麼當它被移除或者替換時,它的生命週期是destoryed。
舉例
// Create fragment and give it an argument specifying the article it should showArticleFragment 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 backtransaction.replace(R.id.fragment_container, newFragment);transaction.addToBackStack(null);// Commit the transactiontransaction.commit();
二 Fragment與Activity通訊
首先說一下兩個Fragment之間互動的問題。
為了重用Fragment UI組件,我們應該把每一個Fragment都構建成完全的自包含的、模組化的組件,定義它們自己的布局與行為。當我們定義好這些模組化的Fragment,我們就可以讓他們關聯Activity,使他們與App的邏輯結合起來,實現全域的複合的UI。
通常,我們想要Fragment之間能相互互動,比如基於使用者事件改變Fragment的內容。所有Fragment之間的互動需要通過它們關聯的activity,兩個Fragment之間不應該直接互動。
2.1 Activity向Fragment傳遞資料
在Activity中建立Bundle資料包,並調用Fragment的setArguments(Bundle bundle)方法即可將Bundle資料包傳遞給Fragment。
舉例
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(); } }}
2.2 Fragment向Activity傳遞資料
在Fragment中定義一個內部回調介面,再讓包含該Fragment的Activity實現該回調介面,這樣Fragment即可調用該回調方法傳遞資料給Activity。
舉例
在Fragment定義了一個介面
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"); } } //Fragment通過回調介面給所屬Activity發送資訊 @Override public void onListItemClick(ListView l, View v, int position, long id) { // Send the event to the host activity mCallback.onArticleSelected(position); }}
Fragment所屬的Activity實現該介面
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 }}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。