2018年6月3日 星期日

[Android Architecture Component]Navigation Fragments

簡介

從Android Studio 3.2開始可以使用Navigation Component(2018/06/04 目前需要使用Canary版本)
這個元件可以簡化程序之間跳轉的呈現,並且有可視的UI可以看到流程
從Android Developer上也可以查看更多介紹 Link



規則

使用這個元件有一些Goodle給的建議規範:
  • The app should have a fixed starting destination
   APP應該給予固定的起始點
  • A stack is used to represent the navigation state of an app
   Navigation是用Stack的方式在導航流程,而且是以"後進先出"的方式堆疊,也就是最後呈現的頁面是在堆疊的最上層(頂部)
  • The Up button never exits your app
   如果使用者目前在起始頁(第一頁),那麼當使用者點擊Back時,不應該退出APP,而是應將使用者導至其他應用頁面
  • Up and Back are equivalent within your app’s task
   同上,點擊Back不應退出APP
  • Deep linking to a destination or navigating to the same destination should yield the same stack
無論使用者從什麼地方進入,都應在相同的堆疊上

Getting Started 開始使用

在Gradle上加入相依:

 
dependencies {

    def nav_version = "1.0.0-alpha01"

    implementation "android.arch.navigation:navigation-fragment:$nav_version" // use -ktx for Kotlin

    implementation "android.arch.navigation:navigation-ui:$nav_version" // use -ktx for Kotlin

}

然後新增一個Navition res檔
對res資料夾右鍵 -> Android Resource File -> Resource Type 選Navition




認識編輯器


  1. 1.Destinations list - 列出在圖形編輯器中的所有目的地。
  2. 2.Graph Editor - Destinations的可視化。
  3. 3.The Attributes Editor - 包含Destinations和action相關的屬性。

建立目的地


點選圖中的圈起來的+,此時若有Fragemnt他就會顯示目前有的,這裡我已經先建立好兩個Fragment(MainFragment、ListFragment)

好了之後我們就可以將他們連結起來

連結後我們就可以準備使用它了

使用

切換至你想要用的Acitvity xml ,加入一個Fragment 元件,如下:
 

<?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:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/my_nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        app:navGraph="@navigation/nav_graph"
        app:defaultNavHost="true"
        />

</android.support.constraint.ConstraintLayout>


其中有兩個重點

  •  app:navGraph="@navigation/nav_graph"
   修改為剛剛創建的Navigation Resource檔案
  •  app:defaultNavHost="true"
   讓你的NavHostFragment可以攔截系統Back事件,你也可以改寫AppCompatActivity.onSupportNavigateUp() 然後使用 NavController.navigateUp 

跳轉Fragment

要切換Fragment是使用NavController 這個Class,有以下幾種方法:

  • NavHostFragment.findNavController(Fragment)
  • Navigation.findNavController(Activity, @IdRes int viewId)
  • Navigation.findNavController(View)

簡單來說可以這樣使用:

viewTransactionsButton.setOnClickListener { view ->


   view.findNavController().navigate(R.id.viewTransactionsAction)

}
以上大致上就是整個流程,也可以上我的GitHub上看範例 有問題或有錯誤歡迎留言討論討論~~

沒有留言:

張貼留言