Navigation
是JetPack
中的一个组件,用于方便的实现页面的导航。
处理应用内导航所需的一切。
Navigation
官网链接:https://developer.android.google.cn/guide/navigation/
1 依赖
implementation'androidx.navigation:navigation-fragment:2.1.0'
2 资源
在res
目录下创建navigation
目录,并且在该目录下创建一个Navigation resource file
的xml
文件

打开你创建的
xml
文件并且选择design
界面

点击某个元素右边中间的小圈连接其他元素添加
action
,这些action
就是你想要的各个元素之间的跳转切换等
切换到
text
界面,自动生成如下代码
<?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.xml"
app:startDestination="@id/helloFragment">
<fragment
android:id="@+id/helloFragment"
android:name="com.zhu.hello.feature.fragment.HelloFragment"
android:label="HelloFragment" >
<action
android:id="@+id/action_helloFragment_to_findFragment"
app:destination="@id/findFragment" />
</fragment>
<fragment
android:id="@+id/findFragment"
android:name="com.zhu.hello.feature.fragment.FindFragment"
android:label="FindFragment">
<action
android:id="@+id/action_findFragment_to_friendFragment"
app:destination="@id/friendFragment" />
</fragment>
<fragment
android:id="@+id/mineFragment"
android:name="com.zhu.hello.feature.fragment.MineFragment"
android:label="fragment_mine"
tools:layout="@layout/fragment_mine">
<action
android:id="@+id/action_mineFragment_to_helloFragment"
app:destination="@id/helloFragment" />
</fragment>
<fragment
android:id="@+id/friendFragment"
android:name="com.zhu.hello.feature.fragment.FriendFragment"
android:label="FriendFragment">
<action
android:id="@+id/action_friendFragment_to_mineFragment"
app:destination="@id/mineFragment" />
</fragment>
</navigation>
app:startDestination="@id/helloFragment"
表示主页面
3 布局
MainActivity
的布局文件activity_main.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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".feature.MainActivity">
<fragment
android:id="@+id/container"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="@navigation/nav" />
</androidx.constraintlayout.widget.ConstraintLayout>
4 实现
比如从HelloFragment
切换到FindFragment
@OnClick(R.id.btn_hello)
public void onViewClicked(View view) {
Navigation.findNavController(view).navigate(R.id.action_helloFragment_to_findFragment);
}
5 演示
点击各个fragment
的button

点击后退按钮

6 本文总结
以上后退和各种操作MainActivity
没有提供任何代码,做起项目更方便。
网友评论