jetpack 获取NavController的3种方式

jetpack里建议ui用fragment组建,但是不像传统的方式自行管理fragment的示例,采用和activity类似的思想,托管给框架,注册给nav.xml,通过NavController来控制fragment,主要是控制跳转。

navigation有2种依赖包
– 基本

    implementation "android.arch.navigation:navigation-fragment:1.0.0-alpha07"
    implementation "android.arch.navigation:navigation-ui:1.0.0-alpha07"
  • KTX
    implementation "android.arch.navigation:navigation-fragment-ktx:1.0.0-alpha07"
    implementation "android.arch.navigation:navigation-ui-ktx:1.0.0-alpha07"

获取方式也自然分2种

  • 基本

通过activity获取
Navigation.java

public static NavController findNavController(@NonNull Activity activity, @IdRes int viewId) 

通过view获取
Navigation.java

public static NavController findNavController(@NonNull View view)

通过Fragment获取
NavHostFragment.java

public static NavController findNavController(@NonNull Fragment fragment)
– KTX

通过activity获取

fun Activity.findNavController(@IdRes viewId: Int): NavController

通过view获取

fun View.findNavController(): NavController

通过Fragment获取

fun Fragment.findNavController(): NavController

jetpack navigation BottomNavigationView不切换可能的坑

navigation文件里定义的item要能在nav.xml里有对应

    <com.google.android.material.bottomnavigation.BottomNavigationView
            android:id="@+id/navigation"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?android:attr/windowBackground"
            app:menu="@menu/navigation"/>

navigation.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
            android:id="@+id/missionFragment"
            android:icon="@drawable/ic_home_black_24dp"
            android:title="任务"/>

    <item
            android:id="@+id/readFragment"
            android:icon="@drawable/ic_dashboard_black_24dp"
            android:title="读卡"/>

</menu>

nav.xml

    <?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/navi_graph"
                app:startDestination="@id/missionFragment">

        <fragment android:id="@+id/missionFragment" android:name="cn.com.gmcc.sign.fragment.MissionFragment"
                  android:label="任务列表" tools:layout="@layout/fragment_mission">
        </fragment>
        <fragment android:id="@+id/readFragment" android:name="cn.com.gmcc.sign.fragment.ReadFragment"
                  android:label="读卡" tools:layout="@layout/fragment_read"></fragment>
    </navigation>