【JetPack】Navigation使用:界面导航+传递参数+动画切换

NavHost: 容器。用于存放每个界面
Fragment:碎片
NavController:控制导航逻辑。控制界面的切入切出。要定义切换的路线。
NvaGraph:以图形化方式定义切换路线

仔细阅读下面的内容,就可以理解 Navigation Graph,NavHostFragment,NavController三者的关系:
当你想切换Fragment时,使用NavController对象,告诉他你想要去Navigation Graph中的哪个Fragment,NavController会将你想去的Fragment展示在NavHostFragment中。

导航的实现步骤

(0)创建空工程

(1)定义两个空的Fragment

(2)创建Navigation资源文件my_nav_graph.xml
注意:my_nav_graph中的id必须与menu中的对应相同,才能使用底部导航栏。否则无反应。
右键res,创建资源文件,Resource Type选Navigation,点击OK添加必要依赖
点击绿色加号,添加fragment,并通过图形操作,定义跳转方向,可以选择每条线的切换动画,也可以修改每个界面的Label标题

(3)定义容器NaviHostFragment
在activity_main.xml中添加NaviHostFragment容器,用于后面存放各个fragment
选择添加my_nav_graph

导航的具体代码

MainActivity.java

package com.dj.navigation;

import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.NavigationUI;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        NavController controller = Navigation.findNavController(this, R.id.fragment); // 参数2是activity_main.xml中定义的NaviHostFragment
        NavigationUI.setupActionBarWithNavController(this, controller); // 这里显示每页的标题,标题内容可以在my_nav_graph的Label中修改
    }

    // 为了让左上方的左箭头生效,点击可退出当前界面,返回上层界面
    @Override
    public boolean onSupportNavigateUp() {
        NavController controller = Navigation.findNavController(this, R.id.fragment);
        return controller.navigateUp();
    }
}

<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/fragment"
        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_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/my_nav_graph" />
androidx.constraintlayout.widget.ConstraintLayout>

HomeFragment.java

package com.dj.navigation;

import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class HomeFragment extends Fragment {


    public HomeFragment() {
        // 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_home, container, false);
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // 定义Button按钮的跳转
        Button button;
        button = getView().findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NavController controller = Navigation.findNavController(v);
                controller.navigate(R.id.action_homeFragment_to_detailFragment);
            }
        });
    }
}

fragment_home.xml


<FrameLayout 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=".HomeFragment">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Home"
            android:textSize="25sp"
            app:layout_constraintBottom_toTopOf="@+id/guideline3"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="@+id/guideline3" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/guideline2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            app:layout_constraintGuide_percent=".6" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/guideline3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            app:layout_constraintGuide_percent=".4" />

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button"
            app:layout_constraintBottom_toTopOf="@+id/guideline2"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="@+id/guideline2" />
    androidx.constraintlayout.widget.ConstraintLayout>
FrameLayout>

DetailFragment.java

package com.dj.navigation;

import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class DetailFragment extends Fragment {

    public DetailFragment() {
        // 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_detail, container, false);
    }

    // 定义Button按钮的跳转
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getView().findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NavController navController = Navigation.findNavController(v);
                navController.navigate(R.id.action_detailFragment_to_homeFragment);
            }
        });
    }
}

fragment_detail.xml


<FrameLayout 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=".DetailFragment">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Detail"
            android:textSize="25sp"
            app:layout_constraintBottom_toTopOf="@+id/guideline5"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="@+id/guideline5" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button"
            app:layout_constraintBottom_toTopOf="@+id/guideline6"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="@+id/guideline6"
            app:layout_constraintVertical_bias="0.25" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/guideline5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            app:layout_constraintGuide_percent="0.4" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/guideline6"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            app:layout_constraintGuide_percent="0.6" />
    androidx.constraintlayout.widget.ConstraintLayout>
FrameLayout>

my_nav_graph.xml
【JetPack】Navigation使用:界面导航+传递参数+动画切换_第1张图片


<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/my_nav_graph"
    app:startDestination="@id/homeFragment">

    <fragment
        android:id="@+id/homeFragment"
        android:name="com.dj.navigation.HomeFragment"
        android:label="Home"
        tools:layout="@layout/fragment_home">
        <action
            android:id="@+id/action_homeFragment_to_detailFragment"
            app:destination="@id/detailFragment"
            app:enterAnim="@anim/nav_default_pop_enter_anim"
            app:exitAnim="@anim/nav_default_pop_exit_anim" />
    fragment>
    <fragment
        android:id="@+id/detailFragment"
        android:name="com.dj.navigation.DetailFragment"
        android:label="Detail"
        tools:layout="@layout/fragment_detail">
        <action
            android:id="@+id/action_detailFragment_to_homeFragment"
            app:destination="@id/homeFragment" />
    fragment>
navigation>

传递参数

(1)给某个Fragment添加一个变量:
在my_nav_graph.xml中,点击detailFragment,右侧Arguments,点+,添加一个变量“name, String, Jack”

public class DetailFragment extends Fragment {
...
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

		// 读取变量值,并设置给textview
        String string = getArguments().getString("name");
        TextView textView = getView().findViewById(R.id.textView2);
        textView.setText(string);

        ...
    }
}

(2)给某条跳转线设置参数
此时已经有了name变量,可以重载默认值

前提是:

HomeFragment.java中
设置跳转方向的时候,用的是:
controller.navigate(R.id.action_homeFragment_to_detailFragment); 
而不是:
controller.navigate(R.id.detailFragment); 

(3)读取HomeFragment中输入的字符串数据,通过bundle传递给DetailFragment

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // 定义Button按钮的跳转
        Button button;
        button = getView().findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取输入框中的非空字符串
                EditText editText = getView().findViewById(R.id.editTextTextPersonName);
                String string = editText.getText().toString();
                if (TextUtils.isEmpty(string)) {
                    Toast.makeText(getActivity(), "请输入名字", Toast.LENGTH_SHORT).show();
                    return;
                }
                // 将字符串中的内容放到bundle中
                Bundle bundle = new Bundle();
                bundle.putString("my_name", string);

                NavController controller = Navigation.findNavController(v);
                controller.navigate(R.id.action_homeFragment_to_detailFragment, bundle); // 将bundle传递给目的界面
            }
        });
    }
}

并且在DetailFragment中读取传过来的参数:

public class DetailFragment extends Fragment {
...
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        
        // 此处读取的是bundle中的值
        String string2 = getArguments().getString("my_name");
        TextView textView = getView().findViewById(R.id.textView2);
        textView.setText(string2);
		...
    }
}

(4)最好的方式,通过ViewModel + LiveData + DataBinding
【JetPack】Navigation使用:界面导航+传递参数+动画切换_第2张图片
在build.gradle(:app)中添加databinding依赖:

android{
...
    buildFeatures{
        dataBinding true
    }
}

重新创建两个Fragment:MasterFragment和ViewModelFragment
MasterFragment.java

package com.dj.navigation;

import android.os.Bundle;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;

import com.dj.navigation.databinding.FragmentMasterBinding;

public class MasterFragment extends Fragment {
    
    public MasterFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        MyViewModel myViewModel;
        myViewModel = ViewModelProviders.of(getActivity()).get(MyViewModel.class);
        FragmentMasterBinding binding;
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_master, container, false);
        binding.setData(myViewModel);
        binding.setLifecycleOwner(getActivity());
        binding.button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NavController controller = Navigation.findNavController(v);
                controller.navigate(R.id.action_masterFragment_to_viewModelFragment);
            }
        });
        binding.seekBar.setProgress(myViewModel.getNumber().getValue());
        binding.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                myViewModel.getNumber().setValue(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        return binding.getRoot();
    }
}

<layout 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">

    <data>
        <variable
            name="data"
            type="com.dj.navigation.MyViewModel"/>
    data>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MasterFragment">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:id="@+id/textView3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@{String.valueOf(data.number)}"
                android:textSize="30sp"
                app:layout_constraintBottom_toTopOf="@+id/seekBar"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="@+id/guideline12" />

            <Button
                android:id="@+id/button3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Button"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.498"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="@+id/guideline13"
                app:layout_constraintVertical_bias="0.086" />

            <SeekBar
                android:id="@+id/seekBar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_constraintBottom_toTopOf="@+id/guideline13"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="@+id/guideline14" />

            <androidx.constraintlayout.widget.Guideline
                android:id="@+id/guideline12"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                app:layout_constraintGuide_percent="0.4" />

            <androidx.constraintlayout.widget.Guideline
                android:id="@+id/guideline13"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                app:layout_constraintGuide_percent=".6" />

            <androidx.constraintlayout.widget.Guideline
                android:id="@+id/guideline14"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                app:layout_constraintGuide_percent="0.5" />

        androidx.constraintlayout.widget.ConstraintLayout>
    FrameLayout>
layout>

ViewModelFragment.java

package com.dj.navigation;

import android.os.Bundle;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.dj.navigation.databinding.FragmentViewModelBinding;

public class ViewModelFragment extends Fragment {

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        MyViewModel myViewModel;
        myViewModel = ViewModelProviders.of(getActivity()).get(MyViewModel.class);
        FragmentViewModelBinding binding;
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_view_model, container, false);
        binding.setData(myViewModel);
        binding.setLifecycleOwner(getActivity());

        binding.button5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NavController controller = Navigation.findNavController(v);
                controller.navigate(R.id.action_viewModelFragment_to_masterFragment);
            }
        });
        return binding.getRoot();
    }
}

<layout 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">

    <data>
        <variable
            name="data"
            type="com.dj.navigation.MyViewModel"/>
    data>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".ViewModelFragment">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <Button
                android:id="@+id/bt_add"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="+"
                android:onClick="@{()->data.add(1)}"
                app:layout_constraintBottom_toTopOf="@+id/guideline8"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="@+id/guideline7"
                app:layout_constraintTop_toTopOf="@+id/guideline9" />

            <TextView
                android:id="@+id/tv_result"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@{String.valueOf(data.number)}"
                android:textSize="30sp"
                app:layout_constraintBottom_toTopOf="@+id/guideline10"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="@+id/guideline10" />

            <Button
                android:id="@+id/bt_minus"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="-"
                android:onClick="@{()->data.add(-1)}"
                app:layout_constraintBottom_toTopOf="@+id/guideline8"
                app:layout_constraintEnd_toStartOf="@+id/guideline7"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="@+id/guideline9" />

            <androidx.constraintlayout.widget.Guideline
                android:id="@+id/guideline7"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                app:layout_constraintGuide_percent="0.5" />

            <androidx.constraintlayout.widget.Guideline
                android:id="@+id/guideline8"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                app:layout_constraintGuide_percent=".6" />

            <androidx.constraintlayout.widget.Guideline
                android:id="@+id/guideline9"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                app:layout_constraintGuide_percent="0.4" />

            <androidx.constraintlayout.widget.Guideline
                android:id="@+id/guideline10"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                app:layout_constraintGuide_percent="0.3" />

            <androidx.constraintlayout.widget.Guideline
                android:id="@+id/guideline11"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                app:layout_constraintGuide_percent="0.7" />

            <Button
                android:id="@+id/button5"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="back"
                app:layout_constraintBottom_toTopOf="@+id/guideline11"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="@+id/guideline11" />
        androidx.constraintlayout.widget.ConstraintLayout>
    FrameLayout>
layout>

MyViewModel.java

package com.dj.navigation;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

public class MyViewModel extends ViewModel {
    public MutableLiveData<Integer> number;

    public MutableLiveData<Integer> getNumber(){
        if(number == null){
            number = new MutableLiveData<>();
            number.setValue(0);
        }
        return number;
    }

    public void add(int x){
        number.setValue(number.getValue() + x);
        if(number.getValue() < 0){
            number.setValue(0);
        }
    }
}

viewmodel_nav_graph.xml
【JetPack】Navigation使用:界面导航+传递参数+动画切换_第3张图片


<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/viewmodel_nav_graph"
    app:startDestination="@id/masterFragment">

    <fragment
        android:id="@+id/masterFragment"
        android:name="com.dj.navigation.MasterFragment"
        android:label="MasterFragment" >
        <action
            android:id="@+id/action_masterFragment_to_viewModelFragment"
            app:destination="@id/viewModelFragment" />
    fragment>
    <fragment
        android:id="@+id/viewModelFragment"
        android:name="com.dj.navigation.ViewModelFragment"
        android:label="fragment_view_model"
        tools:layout="@layout/fragment_view_model" >
        <action
            android:id="@+id/action_viewModelFragment_to_masterFragment"
            app:destination="@id/masterFragment" />
    fragment>
navigation>

MainActivity.java 没有发生任何改变

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        NavController controller = Navigation.findNavController(this, R.id.fragment); // 参数2是activity_main.xml中定义的NaviHostFragment
        NavigationUI.setupActionBarWithNavController(this, controller); // 这里显示每页的标题,标题内容可以在my_nav_graph的Label中修改
    }

    // 为了让左上方的左箭头生效,点击可退出当前界面,返回上层界面
    @Override
    public boolean onSupportNavigateUp() {
        NavController controller = Navigation.findNavController(this, R.id.fragment);
        return controller.navigateUp();
    }
}

activity_main.xml
只需要把navGraph修改为:@navigation/viewmodel_nav_graph


<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/fragment"
        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_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/viewmodel_nav_graph" />
androidx.constraintlayout.widget.ConstraintLayout>

切换动画

(1)新建两个资源文件,类型Animation:
slide_from_left.xml


<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:fromXDelta="-100%"
        android:toXDelta="0%"
        android:duration="300">
    translate>
set>

slide_to_right.xml


<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:fromXDelta="0%"
        android:toXDelta="100%"
        android:duration="300"
        >
    translate>
set>

scale.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <scale
        android:duration="1000"
        android:fromXScale="0.0"
        android:fromYScale="0.0"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toXScale="1.0"
        android:toYScale="1.0"></scale>
</set>

scale_rotation.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <scale
        android:duration="1000"
        android:fromXScale="0.0"
        android:fromYScale="0.0"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toXScale="1.0"
        android:toYScale="1.0"></scale>

    <rotate
        android:duration="1000"
        android:fromDegrees="0"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toDegrees="360"></rotate>
</set>

(2)在my_nav_graph中给某条路线设置进入和退出动画即可。

你可能感兴趣的:(JetPack,Android,android,移动开发,android,studio,Navigation,Jetpack)