Android Jetpack架构组件之Navigation
例子 登录和注册界面切换
Navigation好处
导航架构组件简化了Android应用程序中导航的实现,通过在xml中添加元素并指定导航的起始和目的地,从而在Fragment之间建立连接在Activity中调用xml中设置的导航action从而跳转界面到目的地,简单来说它和之前在活动中调用startActivity的区别就类似于代码布局和xml中layout布局一样,既简单又可视化
Fragment
所使用切换展示的fragment 分别是 HomeFragrmnt ,detalFragment 以及对应的 xml文件
Navhost 类似于栈或者是容器 进行相应操作 ,出栈,近栈 ,Navhost 界面存在主界面中xml文件中
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--类似于这就是一个容器,容器默认显示navation的第一 也就是我写的登录页面-->
<fragment
android:id="@+id/fragment_navigation_login"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="@navigation/nav_login" />
</androidx.constraintlayout.widget.ConstraintLayout>
<?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/nav_login" app:startDestination="@id/loginFragment" tools:ignore="UnusedNavigation"> <fragment android:id="@+id/loginFragment" android:name="com.example.myjeptdemo.LoginFragment" android:label="登录" tools:layout="@layout/fragment_login"> <!-- 其他点击可导致的行为--> <action android:id="@+id/action_loginFragment_to_registerFragment" app:destination="@id/registerFragment" app:enterAnim="@anim/nav_default_pop_enter_anim" app:exitAnim="@anim/nav_default_pop_exit_anim" /> </fragment> <fragment android:id="@+id/registerFragment" android:name="com.example.myjeptdemo.RegisterFragment" android:label="注册" tools:layout="@layout/fragment_register"> <action android:id="@+id/action_registerFragment_to_loginFragment" app:destination="@id/loginFragment" /> </fragment> </navigation>
注意事项
切换使用的fragment 每次都会走 oncreat
详细步骤可参考
https://blog.csdn.net/Alexwll/article/details/83244004