Fragment跳转的骚操作

3,105 阅读6分钟

你还在为Fragment之间的跳转感到疑惑吗?你还在为Fragement的返回而苦恼吗?

那么你的春天来了。。。

Google在2018年I/O大会上推出了一个新的组件Navigation,我是最近才发现的。真的有一种相见恨晚的感觉!

本文知识点

  • Navigation的说明
  • Navigation的简单使用
  • Navigation的注意事项

1. Navigation的说明

Navation提供了单Activity多Fragment之间的转场和栈管理,帮助我们轻松的解决Fragment之间的跳转问题;再也不用add和replace的一些列操作了!使用它之后,你会有一种相见恨晚的感脚的。相信我。。。

2. Navigation的简单使用

首先Navigation是在Android Student 3.2以上才可以使用的。你说你懒,好我给你个地址下载地址 还有一个问题,默认Android Student 是没有开启Navigation的,你可以将Settings->Experimental界面中最下面Enable Navigation Editor勾上即可(要重启才会生效的)。

做好上面的准备之后,我们就可以开始了!!!

盘他

2.1 引入相应的类库

    implementation 'android.arch.navigation:navigation-fragment:1.0.0-alpha09'
    implementation 'android.arch.navigation:navigation-ui:1.0.0-alpha09'

这个是Navigation所需要的类库,直接引入就好了!!!

2.2 创建相应的导航图

这里直接res->New->Android Resource File然后直接进行相应的选择就可以了!

图片展示
把上面的名称换成你想要的名称就可以,别用中文啊。你老大发现了会打你的! 这里为了演示Demo方便,建议你先创建两个Fragment。我这里创建了一个FirstFragment和SecondFragment两个Fragment,方便后面的演示!

图片展示
这里为了方便演示,我就直接先创建了一个Destination相当于创建了一个开始的目标,也就是上面展示的那个页面,其实这种可视化真的是很方便。一会儿我在说代码该怎么写!但是这里有一个点需要注意,因为Navigation 是处理Fragment之前的跳转,所以这里只能以Fragment作为开始的目标,进行跳转!上图目标的右边有一个小圈圈,是可以为了实现跳转的。

展示图片
当你又选择了一个Fragment并且连接了之后,会变成上面的样子。这里有个小技巧说明一下,你可以点击中间的连接线,是可以设置相应的跳转动画。

展示图片
画红框的地方是添加动画的。这里默认的动画,就是一个渐变动画。其实我觉得应该更换一下,这个动画实在是太难看了。。。

上面的步骤都完成了之后我们看一下相应的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"
    app:startDestination="@id/firstFragment">

    <fragment
        android:id="@+id/firstFragment"
        android:name="com.lon.angle.myapplication.FirstFragment"
        android:label="fragment_first"
        tools:layout="@layout/fragment_first">
        <action
            android:id="@+id/action_firstFragment_to_secondFragment"
            app:destination="@id/secondFragment"
            app:enterAnim="@anim/nav_default_enter_anim"
            app:exitAnim="@anim/nav_default_exit_anim"
            app:popEnterAnim="@anim/nav_default_pop_enter_anim"
            app:popExitAnim="@anim/nav_default_pop_exit_anim" />
    </fragment>
    <fragment
        android:id="@+id/secondFragment"
        android:name="com.lon.angle.myapplication.SecondFragment"
        android:label="fragment_second"
        tools:layout="@layout/fragment_second">
        <action
            android:id="@+id/action_secondFragment_to_firstFragment"
            app:destination="@id/firstFragment" />
    </fragment>
</navigation>

说下上面的xml代码:

  • fragment 可以指定一个Fragment你可以理解成在正常的布局文件中的那个fragment
  • tools:layout 这个是指定相应的布局文件的,用于显示。
  • action 这个标签代表一个目标,其实你可以理解成那条线
    • id 那条线的标识,之后会根据这个标识进行跳转的
    • destination 目标id也就是你要跳转的fragment(这里其实也可以是Activity)
    • enterAnim/exitAnim/popEnterAnim/popExitAnim 这几个就是动画了。

基本上就这么多了,剩下的就是处理相应的跳转了。接下来我们看看Activity中的布局是怎么写的!

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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=".Main3Activity">


    <fragment
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/fragment"
        app:defaultNavHost="true"
        app:navGraph="@navigation/nav_test"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

说下这里的几个参数

  • name 这里面是写死的“androidx.navigation.fragment.NavHostFragment”你只要写上这个就可以了
  • defaultNavHost 这个写上true就可以了
  • navGraph 这个是你创建的navigation的xml的名称
  • id 就不说了

这些都完成了,那我们就看一下Fragment怎么实现跳转吧!!!

public class Main3Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);
    }

    @Override
    public boolean onSupportNavigateUp() {
        Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment);
        if(fragment==null){
            return false;
        }
        return NavHostFragment.findNavController(fragment).navigateUp();
    }
}

没错,就直接覆写onSupportNavigateUp这个方法,直接把id填进去就可以了,这里**NavHostFragment.findNavController(fragment).navigateUp();**是初始化的方法。

之后就是相应Fragment中的操作了,我么看一下Fragment的中的内容吧!

public class FirstFragment extends Fragment {


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


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_first, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Button btnNext = view.findViewById(R.id.btn_next);
        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Navigation.findNavController(v).navigate(R.id.action_firstFragment_to_secondFragment);
            }
        });
    }
}

就是一个常规的Fragment,其实最主要的就是Navigation.findNavController(v).navigate(R.id.action_firstFragment_to_secondFragment); 还记得之前action的id吧!这里就是根据那个id进行跳转的!!!可以根据action直接就跳转过去了!

然后我们来看一下第二个Fragment中的代码:

public class SecondFragment extends Fragment {


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


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_second, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Button btnBack = view.findViewById(R.id.btn_back);
        btnBack.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Navigation.findNavController(v).navigate(R.id.action_secondFragment_to_firstFragment);

//                Navigation.findNavController(v).navigateUp();
            }
        });
    }
}

这里在onClick中我写了两行代码,第一行是根据action直接跳转的,和前面的一样我就不说了,第二个是直接跳转到初始状态,因为只涉及到两个Fragment之间的跳转,所以你可以这么写,但是如果过了的话,还是根据action进行跳转比较好!!!

这里给你一张效果图给你演示一下相应的效果:

展示效果图
效果还是比较简单的!!!


基本上通过以上的骚操作就可以进行相应的跳转了。。。

3. Navigation的注意事项

  • 关于传值的问题
  • 关于跳转的问题
  • 待发现的问题。。。

3.1 关于传值的问题

其实很多场景之间Fragment都是有相应传值的问题的,那么怎么进行相应的传值呢?其实就是通过Bundle进行传递的。

		Bundle bundle = new Bundle();
        bundle.putString("aaa","aaa");
        Navigation.findNavController(v).navigate(R.id.action_firstFragment_to_mainActivity,bundle);

就是在你跳转的时候多传入一个Bundle就可以了。

在Fragment接收的话,按照下面的代码进行就可以了。判空自己判断吧!

		Bundle bundle = getArguments();

如果在Activiy中接收的话,按照如下代码进行接收可以了。

		Bundle bundle = getIntent().getExtras();

3.2 关于跳转的问题

其实跳转你要确保相应的action存在,只要action存在根据id进行跳转就可以了,其实有可视化工具的话,这个比较好处理的。

关于Navigation的内容就这么多,可能还有很多不到位的地方,目前我没有发现什么坑,如果有的话可以给我留言,大家一起讨论下。

好了今天就到这里吧!!!