Android 官方組件 Navigation 初使用

Google I/O 大會中國場次已經(jīng)結(jié)束透典,最近也上線了 Android Studio 3.2 版本晴楔,在新版本上有一個谷歌著重推薦的架構(gòu)組件 Navigation。

Navigation 主要是提供了 Fragment 之間的跳轉(zhuǎn)切換峭咒,棧管理滥崩,可以使我們在應(yīng)用中更加輕松的使用 Fragment。先看下我使用兩個 Fragment 實現(xiàn)的最終效果:

image

第一步:想要使用 Navigation讹语,首先要將 Android Studio 升級到 3.2 版本,然后在 Settings 中最后一行找到 Experimental钙皮,對右側(cè) Enable Navigation Editor 打鉤,如下圖所示顽决,然后重啟 studio 使設(shè)置生效短条。

image

第二步: 創(chuàng)建兩個 Fragment,F(xiàn)irstFragment 和 SecondFragment才菠,布局內(nèi)容如下:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".FirstFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="100dp"
        android:text="我是第一個Fragment"/>

    <Button
        android:id="@+id/btn_next"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="跳轉(zhuǎn)到第二個Fragment"
        android:textAllCaps="false"
    />
</FrameLayout>
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:tools="http://schemas.android.com/tools"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             tools:context=".SecondFraagment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_marginTop="100dp"
        android:layout_gravity="center_horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="我是第二個Fragment"/>

    <Button
        android:textAllCaps="false"
        android:id="@+id/btn_back"
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="返回"
    />

</FrameLayout>

第三步: 創(chuàng)建導(dǎo)航視圖文件

在 res 目錄下新建 navigation 文件夾茸时,然后新建一個 navigation 資源文件(需要 Android Studio3.2以上版本)

image

打開資源文件,然后切換為可視化模式赋访,將兩個已經(jīng)創(chuàng)建好的 Fragment 添加進(jìn)去可都,用箭頭連接它們缓待,這樣就為它們綁定了跳轉(zhuǎn)事件。

image

切換為 Text 模式后渠牲,可以看到具體的實現(xiàn)代碼:

<?xml version="1.0" encoding="utf-8"?>
<navigation
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" android:id="@+id/changefragment"
    app:startDestination="@id/firstFragment">

    <fragment
        android:id="@+id/firstFragment"
        android:name="keven.com.myteststudio3l2.FirstFragment"
        android:label="fragment_first"
        tools:layout="@layout/fragment_first">
        <action
            android:id="@+id/action_firstFragment_to_secondFraagment"
            app:destination="@id/secondFraagment"/>
    </fragment>
    <fragment
        android:id="@+id/secondFraagment"
        android:name="keven.com.myteststudio3l2.SecondFraagment"
        android:label="fragment_second_fraagment"
        tools:layout="@layout/fragment_second_fraagment"/>
</navigation>

第四步: 編輯 MainActivity

在 Acitvity 布局文件中添加 fragment 組件旋炒,設(shè)置 name 屬性為 androidx.navigation.fragment.NavHostFragment。在傳統(tǒng)的單 Activity 多 Fragment 場景中签杈,我們往往需要為 Activity 添加一個 FrameLayout 作為 Fragment 的容器瘫镇。在 Navigation 中 HavHostFragment 就是 Fragment 的容器。布局中的 navGraph 屬性建立了與 navigation 資源文件的關(guān)系答姥。

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <fragment
        android:id="@+id/fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/changefragment"
    />

</android.support.constraint.ConstraintLayout>

重寫 onSupportNavigateUp()方法铣除,目的是將 back 事件委托出去。若棧中有兩個以上 Fragment鹦付,點擊 back 鍵就會返回到上一個 Fragment尚粘。

public class MainActivity extends AppCompatActivity {

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

    @Override
    public boolean onSupportNavigateUp() {
        Fragment fragment=getSupportFragmentManager().findFragmentById(R.id.fragment);
        return NavHostFragment.findNavController(fragment).navigateUp();
    }
}

第五步: 在 Fragment 中設(shè)置相應(yīng)的跳轉(zhuǎn)事件。

public class FirstFragment extends Fragment {


    public FirstFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_first, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Button btnNext=view.findViewById(R.id.btn_next);
        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Navigation.findNavController(v).navigate(R.id.action_firstFragment_to_secondFraagment);
            }
        });
    }
}

public class SecondFraagment extends Fragment {


    public SecondFraagment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_second_fraagment, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Button btnBack=view.findViewById(R.id.btn_back);
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Navigation.findNavController(v).navigateUp();
            }
        });
    }
}

如果在界面切換的過程中需要傳值敲长,就把數(shù)據(jù)設(shè)置在 Bundle 中郎嫁,使用如下代碼:

Navigation.findNavController(view).navigate(actionid,bundle);

現(xiàn)在,我們就可以把程序運行起來了潘明,如果需要轉(zhuǎn)場動畫行剂,可以在 Navigation 資源文件的 action 標(biāo)簽下秕噪,添加動畫屬性钳降。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市腌巾,隨后出現(xiàn)的幾起案子遂填,更是在濱河造成了極大的恐慌,老刑警劉巖澈蝙,帶你破解...
    沈念sama閱讀 217,277評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件吓坚,死亡現(xiàn)場離奇詭異,居然都是意外死亡灯荧,警方通過查閱死者的電腦和手機(jī)礁击,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評論 3 393
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來逗载,“玉大人哆窿,你說我怎么就攤上這事±髡澹” “怎么了挚躯?”我有些...
    開封第一講書人閱讀 163,624評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長擦秽。 經(jīng)常有香客問我码荔,道長漩勤,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,356評論 1 293
  • 正文 為了忘掉前任缩搅,我火速辦了婚禮越败,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘誉己。我一直安慰自己眉尸,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,402評論 6 392
  • 文/花漫 我一把揭開白布巨双。 她就那樣靜靜地躺著噪猾,像睡著了一般。 火紅的嫁衣襯著肌膚如雪筑累。 梳的紋絲不亂的頭發(fā)上袱蜡,一...
    開封第一講書人閱讀 51,292評論 1 301
  • 那天,我揣著相機(jī)與錄音慢宗,去河邊找鬼坪蚁。 笑死,一個胖子當(dāng)著我的面吹牛镜沽,可吹牛的內(nèi)容都是我干的敏晤。 我是一名探鬼主播,決...
    沈念sama閱讀 40,135評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼缅茉,長吁一口氣:“原來是場噩夢啊……” “哼嘴脾!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起蔬墩,我...
    開封第一講書人閱讀 38,992評論 0 275
  • 序言:老撾萬榮一對情侶失蹤译打,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后拇颅,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體奏司,經(jīng)...
    沈念sama閱讀 45,429評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,636評論 3 334
  • 正文 我和宋清朗相戀三年樟插,在試婚紗的時候發(fā)現(xiàn)自己被綠了韵洋。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,785評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡黄锤,死狀恐怖搪缨,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情猜扮,我是刑警寧澤勉吻,帶...
    沈念sama閱讀 35,492評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站旅赢,受9級特大地震影響齿桃,放射性物質(zhì)發(fā)生泄漏惑惶。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,092評論 3 328
  • 文/蒙蒙 一短纵、第九天 我趴在偏房一處隱蔽的房頂上張望带污。 院中可真熱鬧,春花似錦香到、人聲如沸鱼冀。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽千绪。三九已至,卻和暖如春梗脾,著一層夾襖步出監(jiān)牢的瞬間荸型,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評論 1 269
  • 我被黑心中介騙來泰國打工炸茧, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留瑞妇,地道東北人。 一個月前我還...
    沈念sama閱讀 47,891評論 2 370
  • 正文 我出身青樓梭冠,卻偏偏與公主長得像辕狰,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子控漠,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,713評論 2 354

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