【Jetpack日记(1)】Navigation的基本使用

前言

开个新坑,上回秋招的时候已经会开始问一些关于Jetpack的一些问题了,然而碰都没碰过,前段时间开始学习,发现网上的质量参差不齐,基本就是照着官网的,还是自己来记录吧,本篇文章将会记录自己学习Jetpack架构组件中Navigation组件的基本使用。

Navigation介绍

首先我们看看Navigation到底是啥,一般查阅资料,我们最权威的还是要从官方文档看起,建议先看一遍视频:

导航介绍页面

Navigation其实就是对Fragment的管理,在以前使用Fragment的时候,尤其是在单Activity+多Fragment的时候,是需要处理多个Fragment的生命周期,很容易出现问题,而Navigation这个组件它提供了多Fragment之间的转场,栈管理,帮助你更轻松的使用Fragment,而且最重要的是它是可视化的(没错)。
Navigation的可视化,第一次看到惊呆了


这样也就可以更加容易的实现单Activity+多Fragment的这种实现模式了,也就是全局只要的一个Activity就行(这里其实还是有争议的)。

Navigation的基本使用

还是老样子,我们根据官方开发文档来看,但是开发文档写的挺难懂的,所以这里再按我自己的理解来使用。
首先要使用Navigation需要build.gradle 文件添加以下依赖项(具体版本根据开发文档来查看):

implementation 'androidx.navigation:navigation-fragment:2.2.0'
implementation 'androidx.navigation:navigation-ui:2.2.0'

然后我们就需要创建一个Navigation了,我们在res文件夹下右键新建一个Android Resource File,名字输入nav_grap,在Resource type类型里面选择Navigation,然后我们就可以看到res文件夹下面有一个新建的navigation文件夹和已经创建好的Navigation了。


Navigation界面

中间一大框框的就是导航图了,也就是可视化界面,左边主要展示这个Navigation的宿主(具体是啥后面再说)和Navigation导航的Fragment。接着我们在创建两个Fragment,名字随意。


Fragment创建

接着我们回到Navigation界面,我们可以看到左上角有一排的按钮,我们点击第一个添加按钮就可以进行Fragment的添加。
Navigation按钮

这时候我们会看到你创建的Fragmt和Activity,我们双击进行全部添加,至于placeholder这个其实就是占位符的意思,我们暂且别管。


添加Fragment

添加完成

Navigation也可以切换到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_graph"
    app:startDestination="@id/oneFragment"
    tools:ignore="UnusedNavigation">
    <fragment
        android:id="@+id/oneFragment"
        android:name="com.ju.navigationdemo.OneFragment"
        android:label="fragment_one"
        tools:layout="@layout/fragment_one" />
    <fragment
        android:id="@+id/twoFragment"
        android:name="com.ju.navigationdemo.TwoFragment"
        android:label="fragment_two"
        tools:layout="@layout/fragment_two" />
    <activity
        android:id="@+id/mainActivity2"
        android:name="com.ju.navigationdemo.MainActivity"
        android:label="activity_main"
        tools:layout="@layout/activity_main" />
</navigation>

看到这里用过Fragment的静态使用方法的人也就明白了,也就是静态添加了Fragment和Activity,接着我们回到视图模式,选型一个Fragment,我们发现它的右边有一个小圆球,这个就是连接的意思,我们可以通过这个小圆球来进行对想要的Fragment的进行跳转等操作,只要拉动这个小圆球选定你要导航的Fragment就好了,我们导航到第二个Fragment,在切换到text模式查看代码。


Navigation连接
<?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_graph"
    app:startDestination="@id/oneFragment"
    tools:ignore="UnusedNavigation">
    <fragment
        android:id="@+id/oneFragment"
        android:name="com.ju.navigationdemo.OneFragment"
        android:label="fragment_one"
        tools:layout="@layout/fragment_one" >
        <action
            android:id="@+id/action_oneFragment_to_twoFragment"
            app:destination="@id/twoFragment" />
    </fragment>
    <fragment
        android:id="@+id/twoFragment"
        android:name="com.ju.navigationdemo.TwoFragment"
        android:label="fragment_two"
        tools:layout="@layout/fragment_two" />
    <activity
        android:id="@+id/mainActivity2"
        android:name="com.ju.navigationdemo.MainActivity"
        android:label="activity_main"
        tools:layout="@layout/activity_main" />
</navigation>

你会发现多了一个action标签,这就是,里面两个属性一个是id(这个很重要),另一个app:destination这个属性就是要导航的Fragmen的id。接着我们回到视图模式,点击Activity,发现Activity是没有这个小圆球的,这也就是说Navigation组件不支持Activity的导航,它主要是管理Fragment的,那么我们就右击删除这个Activity吧。

接着我们需要一个宿主来存放这个Navigation,我们就给他放在MainActivity的布局下(其实就是单Activity+多Fragment的模式):

<?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=".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:navGraph="@navigation/nav_graph" />

</androidx.constraintlayout.widget.ConstraintLayout>

这里的name是指定 Fragment 的类型为NavHostFragment,这个就是Navigation的实现类,类型是Fragment,而defaultNavHost是让Navigation容器处理返回事件,在 Navigation 容器中如果有页面的跳转,点击返回按钮会先处理 容器中 Fragment 页面间的返回,处理完容器中的页面,再处理 Activity 页面的返回。如果值为 false 则直接处理 Activity 页面的返回。最重要的是navGraph这个属性,它就是指定Navigation文件。

接下来就是处理跳转事件了,官方文档说是可以通过以下方法来进行实现:


处理导航事件

写的有点含糊,其实就是通过这个Navigation找到它的Controller来进行跳转操作。我们在第一个Fragment的布局文件中一个Button,然后对这个Button进行控件的跳转。。。

public class OneFragment extends Fragment {


    public OneFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_one, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        view.findViewById(R.id.test).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //进行跳转
                Navigation.findNavController(v).navigate(R.id.action_oneFragment_to_twoFragment);
            }
        });
    }
}

如果是回退的话则是:

Navigation.findNavController(v).navigateUp();

如果是要传递数据给Fragment的话,可以通过Bundle进行传递:

Bundle bundle = new Bundle();
bundle.putInt("test",1);
//进行跳转
Navigation.findNavController(v).navigate(R.id.action_oneFragment_to_twoFragment,bundle);
//进行接收
Bundle bundle = getArguments();
运行结果

然后我们发现一个问题,没有跳转动画,其实我们也可以在Navigation的可视化界面进行设置,点击连接的那跟线,然后在右边的Animations中就可以进行设置了,然后在text模式也会成成相应的代码。


设置跳转动画
//要跳转的action标签会自动生成,也可以自定义anim
<action
            android:id="@+id/action_oneFragment_to_twoFragment"
            app:destination="@id/twoFragment"
            app:enterAnim="@anim/fragment_open_enter"
            app:exitAnim="@anim/fragment_open_exit"
            app:popEnterAnim="@anim/fragment_open_enter"
            app:popExitAnim="@anim/fragment_open_exit" />


Navigation + BottomNavigationView构建导航栏

如果只是最基本的使用那就没意思了,其实这个Navigation是可以配合BottomNavigationView做出导航栏的效果的,BottomNavigationView是谷歌推出的一个底部导航栏的控件,一般是配合Fragment来一起使用的,而且在官网案例中也有这样的使用方法。



新建工程中的Bottom Navigation Activity就是这种方法

我们就自己来实现一个,首先我们在刚刚工程的基础上在创建一个Fragment,这样就是三个Fragment了。


工程项目如图

然后我们在Navigation中把连接的线去掉,并且把第3个Fragment也添加进去。

添加3个Fragment

接着在MainActivity的布局中添加BottomNavigationView:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <fragment
        android:id="@+id/container"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_weight="9"
        android:layout_height="0dp"
        app:defaultNavHost="true"
        app:navGraph="@navigation/nav_graph" />


    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="match_parent"
        android:layout_weight="1"
        android:layout_height="0dp"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_nav_menu" />

</LinearLayout>

BottomNavigationView的menu如下:

//icon随意,id要和Navigation里面3个Fragmet的id要对应!!!!!!!!!!!!
<menu xmlns:android="http://schemas.android.com/apk/res/android">

<item
    android:id="@+id/oneFragment"
    android:icon="@drawable/ic_home_black_24dp"
    android:title="一" />

<item
    android:id="@+id/twoFragment"
    android:icon="@drawable/ic_dashboard_black_24dp"
    android:title="二" />

<item
    android:id="@+id/threeFragment"
    android:icon="@drawable/ic_notifications_black_24dp"
    android:title="三" />

</menu>

然后在MainActivity输入以下代码:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获得BottomNavigationView
        BottomNavigationView navView = findViewById(R.id.nav_view);
        //获得Navigation的Control
        NavController navController = Navigation.findNavController(this,R.id.container);
        //绑定
        NavigationUI.setupWithNavController(navView,navController);
        //获取顶部appBar
        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.oneFragment, R.id.twoFragment, R.id.threeFragment)
                .build();
        //绑定
        NavigationUI.setupActionBarWithNavController(this,navController,appBarConfiguration);
    }

}

最终运行结果


参考

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,117评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,963评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,897评论 0 240
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,805评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,208评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,535评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,797评论 2 311
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,493评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,215评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,477评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,988评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,325评论 2 252
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,971评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,807评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,544评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,455评论 2 266

推荐阅读更多精彩内容