手把手教你使用Android官方组件Navigation

Google 2018 I/O大会上,谷歌隆重推出一个新的架构组件:Navigation。从名字上可以看出他是一个导航,其实我们可以把它理解为FragmentNavigation。它提供了多Fragment之间的转场,栈管理,帮助你更轻松的使用Fragment。在以后抽屉式导航栏,底部、顶部导航栏的需求中我们可以尝试使用这个新组件。甚至,你可以尝试写一个单Activity的应用。

下面是我写的一个Sample,我将引导大家去实现这个小功能。


使用Navigation需要AndroidStudio的版本3.2以上,下面的网址可以下载最新的AndroidStudio

http://www.androiddevtools.cn/

第一步:创建两个Fragment,FristFragment和SecondFragment

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".FirstFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_marginTop="100dp"
        android:layout_gravity="center_horizontal"
        android:text="我是第一个Fragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:textAllCaps="false"
        android:id="@+id/btn_next"
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="跳转到第二个Fragment" />

</FrameLayout>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".SecondFragment">

    <!-- TODO: Update blank fragment layout -->

    <TextView
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="100dp"
        android:text="我是第二个Fragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:layout_gravity="center"
        android:id="@+id/btn_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="返回" />

</FrameLayout>

第二步:创建导航视图文件

在res目录下新建navigation文件夹,然后新建一个navigation资源文件(需要AndroidStudio3.2以上版本)


打开资源文件,切换为design可视化编辑模式,在这个界面,我们可以任意添加Fragment和Activity,用箭头线连接它们,就为它们绑定了跳转事件。


切换为Text模式,下面就是自动编辑好的代码。action标签描述的Fragment转场事件,在里面我们除了可以设置目标Fragment之外,还可以设置转场动画和启动模式。

<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.example.navigation.FirstFragment"
        android:label="fragment_first"
        tools:layout="@layout/fragment_first" >
        <action
            android:id="@+id/action_firstFragment_to_secondFragment"
            app:destination="@id/secondFragment" />
    </fragment>
    <fragment
        android:id="@+id/secondFragment"
        android:name="com.example.navigation.SecondFragment"
        android:label="fragment_second"
        tools:layout="@layout/fragment_second" >
    </fragment>
</navigation>

第三步:编辑MainActivity

在Acitvity布局文件中添加fragment组件,设置name属性为androidx.navigation.fragment.NavHostFragment。在传统的单Activity多Fragment场景中,我们往往需要为Activity添加一个FrameLayout作为Fragment的容器。在Navigation中HavHostFragment就是Fragment的容器。布局中的navGraph属性建立了与navigation资源文件的关系。

<?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=".MainActivity">

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

</android.support.constraint.ConstraintLayout>

重写onSupportNavigateUp()方法,目的是将back事件委托出去。若栈中有两个以上Fragment,点击back键就会返回到上一个Fragment。

public class MainActivity extends AppCompatActivity {

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

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

第四步:在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);
            }
        });
    }
}
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).navigateUp();
            }
        });
    }
}

可以看到,关键API就是一行,界面切换如此简单。如果需要传值,把数据设置在Bundle中,使用以下api即可

Navigation.findNavController(view).navigate(actionid,bundle);

至此,我们就可以把程序运行起来。如果需要添加转场动画,需要在navigation资源文件的action标签下,添加动画属性。

<action
            app:enterAnim="@anim/slide_in_right"
            app:exitAnim="@anim/slide_out_left"
            app:popEnterAnim="@anim/slide_in_left"
            app:popExitAnim="@anim/slide_out_right"
            android:id="@+id/action_firstFragment_to_secondFragment"
            app:destination="@id/secondFragment" />

哇!跳转,传值,管理栈,还有转场动画!简直跟Activity的使用一模一样。从此,Fragment除了拥有自身的优点之外,还get了Activity的技能,我们在构建App的时候是不是可以更加肆意得使用Fragment呢?


  • 14
    点赞
  • 56
    收藏
    觉得还不错? 一键收藏
  • 15
    评论
Android Navigation 是一个用于管理应用程序导航的框架,它可以帮助您轻松地实现常见的导航模式,例如抽屉导航、选项卡导航、底部导航和导航折叠等。 以下是使用 Android Navigation 进行导航的一般步骤: 1. 添加 Navigation 组件库:在 build.gradle 文件中添加以下依赖项: ``` dependencies { def nav_version = "2.3.1" implementation "androidx.navigation:navigation-fragment-ktx:$nav_version" implementation "androidx.navigation:navigation-ui-ktx:$nav_version" } ``` 2. 创建导航图:在 res 文件夹中创建一个名为 nav_graph.xml 的 XML 文件。在此文件中,您可以定义应用程序的所有目标目的地以及它们之间的导航关系。 3. 配置 NavHost:在您的布局文件中添加一个 NavHostFragment,它将负责管理您的应用程序的导航。例如: ``` <fragment android:id="@+id/nav_host_fragment" android:name="androidx.navigation.fragment.NavHostFragment" android:layout_width="match_parent" android:layout_height="match_parent" app:navGraph="@navigation/nav_graph" /> ``` 4. 配置导航栏:在您的 Activity 或 Fragment使用 Navigation UI 库配置您的导航栏。例如: ``` val navController = findNavController(R.id.nav_host_fragment) bottom_nav.setupWithNavController(navController) ``` 5. 导航:使用 NavController 对象执行导航操作。例如,您可以使用以下代码在应用程序中导航到目标目的地: ``` findNavController().navigate(R.id.action_homeFragment_to_detailFragment) ``` 这是一个简单的例子,但是使用 Android Navigation 进行导航可以更加复杂。您可以在官方文档中找到更多信息和示例:https://developer.android.com/guide/navigation/

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值