Android Fragment 簡介及使用示例(一)

關(guān)于 Fragment 可以歸納出如下特征:

  1. Fragment 總是作為 Activity 界面的組成部分。Fragment 可以調(diào)用 getActivity() 方法獲取它所在的 Activity系宜,Activity 可調(diào)用 FragmentManager 的 findFragmentById() 或 findFragmentByTag() 方法來獲取 Fragment癌椿。在界面布局文件中使用 <fragment ... /> 元素添加 Fragment 時啡氢,可以為 <fragment ... /> 元素指定 android:id 或者 android:tag 屬性卵佛,這兩個屬性都可以用于標識該 Fragment,之后可以使用 findFragmentById() 或 findFragmentByTag() 方法來獲取指定的 Fragment年堆;
  2. 在 Activity 運行的過程中斑匪,可以調(diào)用 FragmentManager 的 add()呐籽、remove()、replace() 方法動態(tài)地添加蚀瘸、刪除或替換 Fragment狡蝶;
  3. 一個 Activity 可以同時組合多個 Fragment;同時贮勃,一個 Fragment 也可以被多個 Activity 復(fù)用贪惹;
  4. Fragment 可以響應(yīng)自己的輸入事件,并擁有自己的生命周期寂嘉,但是它們的生命周期直接被所屬的 Activity 的生命周期控制馍乙。

為了在 Activity 中顯示 Fragment,還必須將 Fragment 添加到 Activity 中垫释。將 Fragment 添加到 Activity 中有如下兩種方式:

  1. 在布局文件中使用 <fragment ... /> 元素添加 Fragment,<fragment ... /> 元素的 android:name 屬性指定 Fragment 的實現(xiàn)類撑瞧;
  2. 在 Java 代碼中通過 FragmentTransaction 對象的 add() 方法來添加 Fragment棵譬。Activity 的 getFragmentManager() 方法可以返回 FragmentManager 對象,F(xiàn)ragmentManager 對象的 beginTransaction() 方法即可開啟并返回 FragmentTransaction 對象预伺。

Fragment 與 Activity 之間傳遞數(shù)據(jù)

  1. Activity 向 Fragment 傳遞數(shù)據(jù):在 Activity 中創(chuàng)建 Bundle 數(shù)據(jù)包订咸,并調(diào)用 Fragment 的 setArgument(Bundle bundle) 方法即可將 Bundle 數(shù)據(jù)包傳給 Fragment。
  2. Fragment 向 Activity 傳遞數(shù)據(jù) 或 Activity 需要在 Fragment 運行中進行實時通信:在 Fragment 中定義一個內(nèi)部回調(diào)接口酬诀,再讓包含該 Fragment 的 Activity 實現(xiàn)該回調(diào)接口脏嚷,這樣 Fragment 即可調(diào)用該回調(diào)接口的方法將數(shù)據(jù)傳給 Activity。

FragmentManager 可以完成如下的功能:

  1. 使用 findFragmentById() 或 findFragmentByTag() 方法來獲取指定的 Fragment瞒御;
  2. 調(diào)用 popBackStack() 方法將 Fragment 從后臺棧中彈出(類似用戶按下 BACK 鍵)父叙;
  3. 調(diào)用 addOnBackStackChangeListener() 注冊一個監(jiān)聽器,用于監(jiān)聽后臺棧的變化。

如果我們需要添加趾唱、刪除涌乳、替換 Fragment,則需要使用 FragmentTransaction 對象甜癞,它 代表 Activity 對 Fragment 執(zhí)行多個改變夕晓。我們可以通過如下方法獲取 FragmentTransaction 對象:

FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();

在調(diào)用 commit() 方法之前,我們也可以調(diào)用 addToBackStack() 方法將事務(wù)添加到 back 棧中悠咱,該棧由 Activity 負責(zé)管理蒸辆,這樣允許用戶按下 BACK 鍵返回到上一個 Fragment 的狀態(tài)。
示例代碼:

FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.book_detail_container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();

下面是源代碼部分###

首先是 fragment_book_detail.xml 布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/book_title"
        android:padding="16dp"
        style="?android:attr/textAppearanceLarge"
        />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/book_desc"
        android:padding="16dp"
        style="?android:attr/textAppearanceMedium"
        />

</LinearLayout>

接下來是 activity_book_twopane.xml 布局文件:

<?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"
    android:layout_marginStart="16dp"
    android:layout_marginEnd="16dp"
    android:divider="?android:attr/dividerHorizontal"
    android:showDividers="middle"
    >

    <fragment
        android:name="com.toby.personal.testlistview.BookListFragment"
        android:id="@+id/book_list"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        />

    <FrameLayout
        android:id="@+id/book_detail_container"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="3"
        />

</LinearLayout>

接下來析既,是 BookContent.java 文件:

package com.toby.personal.testlistview;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by toby on 17-3-29.
 */

class BookContent {

    static class Book {
        public Integer id;
        String title;
        String desc;

        Book(Integer id, String title, String desc) {
            this.id = id;
            this.title = title;
            this.desc = desc;
        }

        @Override
        public String toString() {
            return title;
        }
    }

    static List<Book> ITEMS = new ArrayList<>();
    static Map<Integer, Book> ITEM_MAP = new HashMap<>();

    static {
        addItem(new Book(1, "小狗錢錢", "理財入門讀物"));
        addItem(new Book(2, "小狗錢錢的爸爸", "理財入門讀物"));
        addItem(new Book(3, "窮爸爸和富爸爸", "理財入門讀物"));
    }

    private static void addItem(Book book) {
        ITEMS.add(book);
        ITEM_MAP.put(book.id, book);
    }

}

接下來躬贡,是 BookListFragment.java 文件:

package com.toby.personal.testlistview;

import android.app.ListFragment;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

/**
 * Created by toby on 17-3-29.
 */

public class BookListFragment extends ListFragment {

    private Callbacks callbacks;

    interface Callbacks {
        void onItemSelected(Integer id);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setListAdapter(new ArrayAdapter<>(getActivity(),
                android.R.layout.simple_list_item_activated_1,
                android.R.id.text1, BookContent.ITEMS));
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (!(context instanceof Callbacks)){
            throw new IllegalStateException("Callbacks interface must be implemented!");
        }

        callbacks = (Callbacks) context;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        callbacks = null;
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        callbacks.onItemSelected(BookContent.ITEMS.get(position).id);
    }

    public void setActivateOnItemClick(boolean activateOnItemClick) {
        getListView().setChoiceMode(activateOnItemClick ?
                ListView.CHOICE_MODE_SINGLE: ListView.CHOICE_MODE_NONE);
    }

}

接下來,是 BookDetailFragment.java 文件:

package com.toby.personal.testlistview;

import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * Created by toby on 17-3-29.
 */

public class BookDetailFragment extends Fragment {

    final public static String ITEM_ID = "item_id";

    private BookContent.Book book;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments().containsKey(ITEM_ID)) {
            book = BookContent.ITEM_MAP.get(getArguments().getInt(ITEM_ID));
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_book_detail, container, false);

        if (book != null) {
            ((TextView) rootView.findViewById(R.id.book_title)).setText(book.title);
            ((TextView) rootView.findViewById(R.id.book_desc)).setText(book.desc);
        }

        return rootView;
    }
}

接下來渡贾,是 SelectBookActivity.java 文件:

package com.toby.personal.testlistview;

import android.app.Activity;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.annotation.Nullable;

/**
 * Created by toby on 17-3-29.
 */

public class SelectBookActivity extends Activity implements BookListFragment.Callbacks {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_twopane);
    }

    @Override
    public void onItemSelected(Integer id) {
        Bundle arguments = new Bundle();
        arguments.putInt(BookDetailFragment.ITEM_ID, id);
        BookDetailFragment fragment = new BookDetailFragment();
        fragment.setArguments(arguments);
        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.book_detail_container, fragment);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }
}

最后逗宜,調(diào)整 AndroidManifest.xml 文件:

        <activity android:name=".SelectBookActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

程序在虛擬機上的運行效果:

程序在虛擬機上的運行效果

參考文獻:《瘋狂Android講義(第2版)》

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市空骚,隨后出現(xiàn)的幾起案子纺讲,更是在濱河造成了極大的恐慌,老刑警劉巖囤屹,帶你破解...
    沈念sama閱讀 218,386評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件熬甚,死亡現(xiàn)場離奇詭異,居然都是意外死亡肋坚,警方通過查閱死者的電腦和手機乡括,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,142評論 3 394
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來智厌,“玉大人诲泌,你說我怎么就攤上這事∠撑簦” “怎么了敷扫?”我有些...
    開封第一講書人閱讀 164,704評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長诚卸。 經(jīng)常有香客問我葵第,道長,這世上最難降的妖魔是什么合溺? 我笑而不...
    開封第一講書人閱讀 58,702評論 1 294
  • 正文 為了忘掉前任卒密,我火速辦了婚禮,結(jié)果婚禮上棠赛,老公的妹妹穿的比我還像新娘哮奇。我一直安慰自己膛腐,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,716評論 6 392
  • 文/花漫 我一把揭開白布屏镊。 她就那樣靜靜地躺著依疼,像睡著了一般。 火紅的嫁衣襯著肌膚如雪而芥。 梳的紋絲不亂的頭發(fā)上律罢,一...
    開封第一講書人閱讀 51,573評論 1 305
  • 那天,我揣著相機與錄音棍丐,去河邊找鬼误辑。 笑死,一個胖子當(dāng)著我的面吹牛歌逢,可吹牛的內(nèi)容都是我干的巾钉。 我是一名探鬼主播,決...
    沈念sama閱讀 40,314評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼秘案,長吁一口氣:“原來是場噩夢啊……” “哼砰苍!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起阱高,我...
    開封第一講書人閱讀 39,230評論 0 276
  • 序言:老撾萬榮一對情侶失蹤赚导,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后赤惊,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體吼旧,經(jīng)...
    沈念sama閱讀 45,680評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,873評論 3 336
  • 正文 我和宋清朗相戀三年未舟,在試婚紗的時候發(fā)現(xiàn)自己被綠了圈暗。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,991評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡裕膀,死狀恐怖员串,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情昼扛,我是刑警寧澤昵济,帶...
    沈念sama閱讀 35,706評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站野揪,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏瞧栗。R本人自食惡果不足惜斯稳,卻給世界環(huán)境...
    茶點故事閱讀 41,329評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望迹恐。 院中可真熱鬧挣惰,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,910評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至竖幔,卻和暖如春板乙,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背拳氢。 一陣腳步聲響...
    開封第一講書人閱讀 33,038評論 1 270
  • 我被黑心中介騙來泰國打工募逞, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人馋评。 一個月前我還...
    沈念sama閱讀 48,158評論 3 370
  • 正文 我出身青樓放接,卻偏偏與公主長得像,于是被迫代替她去往敵國和親留特。 傳聞我的和親對象是個殘疾皇子纠脾,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,941評論 2 355

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