android Fragment

Fragment 表示 Activity 中的行為或用戶界面部分。您可以將多個Fragment組合在一個 Activity 中來構(gòu)建多窗格 UI,以及在多個 Activity 中重復使用某個Fragment。
Fragment必須始終嵌入在 Activity 中,其生命周期直接受宿主 Activity 生命周期的影響。

向 Activity 添加Fragment

通常,F(xiàn)ragment向宿主 Activity 貢獻一部分 UI,作為 Activity 總體視圖層次結(jié)構(gòu)的一部分嵌入到 Activity 中。可以通過兩種方式向 Activity 布局添加Fragment:

  1. 在 Activity 的布局文件內(nèi)聲明Fragment
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <fragment android:name="com.example.TestFragment"
            android:id="@+id/list"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="match_parent" />
</LinearLayout>

android:name 屬性指定要在布局中實例化的 Fragment 類。

  1. 通過編程方式將片段添加到某個現(xiàn)有 ViewGroup
    想在Activity 中執(zhí)行Fragment事務(如添加、刪除或替換Fragment),必須使用 FragmentTransaction 。可以像下面這樣從 Activity 獲取一個 FragmentTransaction 實例:
FragmentManager fragmentManager = getFragmentManager()  //getSupportFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

可以使用 add() 方法添加一個Fragment,指定要添加的Fragment以及將其插入哪個視圖。

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

傳遞到 add() 的第一個參數(shù)是 ViewGroup,即應該放置Fragment的位置,由資源 ID 指定,第二個參數(shù)是要添加的Fragment。一旦通過 FragmentTransaction 做出了更改,就必須調(diào)用 commit() 以使更改生效。
在調(diào)用 commit() 之前,可以調(diào)用 addToBackStack()方法將事務添加到Fragment事務返回棧。 該返回棧由 Activity 管理,允許用戶通過按“返回” 按鈕返回上一Fragment狀態(tài)。

Fragment newFragment = new ExampleFragment();
//
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
//
transaction.commit();

上例中,newFragment 會替換目前在 R.id.fragment_container ID 所標識的布局容器中的任何片段(如有)。通過調(diào)用 addToBackStack() 可將替換事務保存到返回棧,以便用戶能夠通過按“返回” 按鈕撤消事務并回退到上一片段。

Fragment與Activity間通信

Fragment可以通過 getActivity() 訪問 Activity 實例,并輕松地執(zhí)行在 Activity 布局中查找視圖等任務。
View listView = getActivity().findViewById(R.id.list);
Activity 也可以使用 findFragmentById() 或 findFragmentByTag(),通過從 FragmentManager 獲取對 Fragment 的引用來調(diào)用片段中的方法。

ExampleFragment fragment = (ExampleFragment) getFragmentManager().
                                              findFragmentById(R.id.example_fragment);

Fragment聲明周期

Fragment必須是依存于Activity而存在的,因此Activity的生命周期會直接影響到Fragment的生命周期。



Activity 生命周期與片段生命周期之間的最顯著差異在于它們在其各自返回棧中的存儲方式。 默認情況下,Activity 停止時會被放入由系統(tǒng)管理的 Activity 返回棧(以便用戶通過“返回” 按鈕回退到Activity)。不過,僅當您在刪除片段的事務執(zhí)行期間通過調(diào)用 addToBackStack() 顯式請求保存實例時,系統(tǒng)才會將片段放入由宿主 Activity 管理的返回棧。

創(chuàng)建Fragment

要想創(chuàng)建片段,必須創(chuàng)建 Fragment 的子類或者它的子類(如DialogFragmentListFragmentPreferenceFragment)的子類。

通常,至少應實現(xiàn)以下生命周期方法:

  • onCreate():應該在方法內(nèi)內(nèi)初始化想在fragment暫停或停止后恢復時保留的必需片段組件。
  • onCreateView():系統(tǒng)會在Fragment 首次繪制其用戶界面時調(diào)用此方法。 要想為Fragment 繪制 UI,從此方法中返回的 View 必須是Fragment 布局的根視圖。如果Fragment 未提供 UI,可以返回 null。
  • onPause():通常應該在此方法內(nèi)確認在當前用戶會話結(jié)束后仍然有效的任何更改(因為用戶可能不會返回)。

下面是創(chuàng)建的一個Fragment

public class SecondFragment extends Fragment {
    private static final String TEXT = "text";
    private String mStr;

    public SecondFragment() {
    }

    //在其他地方想要初始化fragment不推薦直接用new Fragment()
    //推薦使用一下方式獲得fragment
    public static SecondFragment newInstance(String text) {
        SecondFragment fragment = new SecondFragment();

        Bundle args = new Bundle();
        args.putString(TEXT, text);
        fragment.setArguments(args);

        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        Log.i(TAG, "onCreate()");
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mStr = getArguments().getString(TEXT);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
            savedInstanceState) {
        Log.i(TAG, "onCreateView()");
        View v = inflater.inflate(R.layout.fragment_second, container, false);
        TextView textView = (TextView)v.findViewById(R.id.second_text);
        textView.setText(mStr);
        return v;
    }
}

fragment的布局文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
    <TextView
        android:id="@+id/second_text"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:textSize="25sp"/>
</RelativeLayout>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容