2023年12月29日 星期五

【Android】建立一個簡單的 Android -> Fragment 、 Navigation


建置步驟

  • 新增兩個空 Fragment (File > New > Fragment > Fragment (Blank) )
  • 設定環境
    1. implementation ("androidx.navigation:navigation-fragment-ktx:2.5.3")
      implementation ("androidx.navigation:navigation-ui-ktx:2.5.3")
  • 新增導航圖
    1. 在「Project」(專案) 視窗的 res 目錄中,按一下滑鼠右鍵並依序選取「New」(新增) >「Android 資源檔案」(Android Resource File)。畫面上會顯示「New Resource File」(新增資源檔案) 對話方塊。
    2. 在「File Name」(檔案名稱) 欄位中輸入名稱,例如「nav_graph」。
    3. 從「Resource Type」(資源類型) 下拉式清單中選取「Navigation」(導覽),然後按一下「OK」(確定)。
新增第一個導覽圖時,Android Studio 會在 res 目錄中建立 navigation 資源目錄。這個目錄包含您的導覽圖資源檔案 (例如 nav_graph.xml)。

  •  在 Activity 中新增 (可以透過 design 版面直接拖曳加入 XML)
    • <androidx.fragment.app.FragmentContainerView
              android:id="@+id/nav_host_fragment"
              android:name="androidx.navigation.fragment.NavHostFragment"
              android:layout_width="0dp"
              android:layout_height="0dp"
              app:layout_constraintLeft_toLeftOf="parent"
              app:layout_constraintRight_toRightOf="parent"
              app:layout_constraintTop_toTopOf="parent"
              app:layout_constraintBottom_toBottomOf="parent"
      
              app:defaultNavHost="true"
              app:navGraph="@navigation/nav_graph" />
      • app:navGraph 屬性會將 NavHostFragment 與導覽圖表建立關聯。導覽圖表會指定使用者能瀏覽這個 NavHostFragment 中的所有到達網頁。
      • app:defaultNavHost="true" 屬性可確保 NavHostFragment 攔截系統返回按鈕。請注意,只有一個 NavHost 可以設為預設。如果您在同一個版面配置中有多個主機 (例如雙窗格版面配置),請務必只指定一個預設 NavHost。
  • 新增 Fragment 到導航圖 、設定起始頁 (Assign Start Destination)
  • 在導航圖中,拉出連結頁面的鏡頭(路徑)

使用導航跳轉頁面

例如 : 
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val button = view?.findViewById<Button>(R.id.button)
        button?.setOnClickListener {
            Log.d("button","clicked")
            findNavController().navigate(R.id.action_blankFragment_to_blankFragment2)
        }
    }

其他方式與 Safe Args 的使用方式可見參考資料

其他參考資料


0 comments:

張貼留言