2

我用导航组件设置了一个底部导航视图。片段之间的用户导航工作正常。

问题是通过底部导航视图的导航不会播放导航组件中配置的动画,即,在正确触摸卡片时以幻灯片样式设置动画,单击底部导航视图中的按钮以淡入淡出样式设置动画,覆盖操作在导航组件中定义的属性。

不一致的动画

res/menu/bottom_navigation.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item android:id="@+id/home_fragment"
        android:title="@string/bottom_navigation_home_title"
        android:icon="@drawable/ic_home"
        app:showAsAction="ifRoom" />

    <item android:id="@+id/schedule_fragment"
        android:title="@string/bottom_navigation_schedule_title"
        android:icon="@drawable/ic_schedule"
        app:showAsAction="ifRoom" />
</menu>

res/anim/slide_in_left.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:fromXDelta="-100%"
        android:toXDelta="0%"
        android:fromYDelta="0%"
        android:toYDelta="0%"
        android:duration="700" />
</set>

res/anim/slide_in_right.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:fromXDelta="100%"
        android:toXDelta="0%"
        android:fromYDelta="0%"
        android:toYDelta="0%"
        android:duration="700" />
</set>

res/anim/slide_out_left.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:fromXDelta="0%"
        android:toXDelta="-100%"
        android:fromYDelta="0%"
        android:toYDelta="0%"
        android:duration="700" />
</set>

res/anim/slide_out_right.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:fromXDelta="0%"
        android:toXDelta="100%"
        android:fromYDelta="0%"
        android:toYDelta="0%"
        android:duration="700" />
</set>

res/navigation/nav_graph.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"
    android:id="@+id/nav_graph"
    app:startDestination="@id/home_fragment">

    <fragment
        android:id="@+id/home_fragment"
        android:name="com.sslabs.whatsappcleaner.ui.HomeFragment"
        android:label="home_fragment"
        tools:layout="@layout/fragment_home">
        <action
            android:id="@+id/action_home_fragment_to_schedule_fragment"
            app:destination="@id/schedule_fragment"
            app:enterAnim="@anim/slide_in_right"
            app:exitAnim="@anim/slide_out_left"
            app:popEnterAnim="@anim/slide_in_left"
            app:popExitAnim="@anim/slide_out_right"
            app:popUpTo="@id/home_fragment" />
    </fragment>
    <fragment
        android:id="@+id/schedule_fragment"
        android:name="com.sslabs.whatsappcleaner.ui.ScheduleFragment"
        android:label="schedule_fragment"
        tools:layout="@layout/fragment_schedule">
    </fragment>
</navigation>

res/layout/fragment_home.xml

<?xml version="1.0" encoding="utf-8"?>
<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">

    <com.google.android.material.card.MaterialCardView
        android:id="@+id/home_schedule_card"
        android:layout_width="344dp"
        android:layout_height="148dp"
        app:cardBackgroundColor="@android:color/holo_blue_dark"
        app:rippleColor="@android:color/holo_orange_dark" />
</layout>

资源/布局/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<layout>

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

        <fragment
            android:id="@+id/nav_host_fragment"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_height="0dp"
            android:layout_width="match_parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toTopOf="@id/bottom_navigation"
            app:defaultNavHost="true"
            app:navGraph="@navigation/nav_graph"/>

        <com.google.android.material.bottomnavigation.BottomNavigationView
            android:id="@+id/bottom_navigation"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_constraintBottom_toBottomOf="parent"
            app:menu="@menu/bottom_navigation" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

com.sslabs.whatsappcleaner.ui.MainActivity

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding: ActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
        val navController: NavController = Navigation.findNavController(this, R.id.nav_host_fragment)
        NavigationUI.setupWithNavController(binding.bottomNavigation, navController)
    }
}

com.sslabs.whatsappcleaner.ui.HomeFragment

class HomeFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val binding: FragmentHomeBinding = DataBindingUtil.inflate(
            inflater, R.layout.fragment_home, container, false)

        binding.homeScheduleCard.setOnClickListener {
            findNavController().navigate(HomeFragmentDirections.actionHomeFragmentToScheduleFragment())
        }

        return binding.root
    }
}
4

1 回答 1

3

解决方案

尝试第一次尝试后,仍会播放默认动画,而不是在 action 中指定的动画(淡入淡出)

显然,action_id仅用于destination,而不是anims.

由于默认动画仍在播放,我打开了NavigationUI.java. 以下是:

public static boolean onNavDestinationSelected(@NonNull MenuItem item,
        @NonNull NavController navController) {
    NavOptions.Builder builder = new NavOptions.Builder()
            .setLaunchSingleTop(true)
            .setEnterAnim(R.anim.nav_default_enter_anim)
            .setExitAnim(R.anim.nav_default_exit_anim)
            .setPopEnterAnim(R.anim.nav_default_pop_enter_anim)
            .setPopExitAnim(R.anim.nav_default_pop_exit_anim);
    if ((item.getOrder() & Menu.CATEGORY_SECONDARY) == 0) {
        builder.setPopUpTo(findStartDestination(navController.getGraph()).getId(), false);
    }
    NavOptions options = builder.build();
    try {
        //TODO provide proper API instead of using Exceptions as Control-Flow.
        navController.navigate(item.getItemId(), null, options);
        return true;
    } catch (IllegalArgumentException e) {
        return false;
    }
}

如您所知,在 中,正在设置NavOptions.Builder默认值。anims

您使用的解决方法对我来说并不令人满意。因此,我冒昧地创建了一个BottomNavigationUI可以执行 . 功能的类NavigationUI,但anims在可用时使用自定义。

不同之处在于onNavDestinationSelected. 请注意,这NavigationUI是最终的,所以我无法覆盖它。

BottomNavigationUI.class

// don't forget your package

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.navigation.NavAction;
import androidx.navigation.NavController;
import androidx.navigation.NavDestination;
import androidx.navigation.NavGraph;
import androidx.navigation.NavOptions;

import com.google.android.material.bottomnavigation.BottomNavigationView;

import java.lang.ref.WeakReference;
import java.util.Set;

public class BottomNavigationUI {

    private BottomNavigationUI() {
    }

    public static boolean onNavDestinationSelected(@NonNull MenuItem item,
                                                   @NonNull NavController navController) {
        int resId = item.getItemId();

        Bundle args = null;
        NavOptions options;

        NavOptions.Builder optionsBuilder = new NavOptions.Builder()
                .setLaunchSingleTop(true)
                .setEnterAnim(R.anim.nav_default_enter_anim)
                .setExitAnim(R.anim.nav_default_exit_anim)
                .setPopEnterAnim(R.anim.nav_default_pop_enter_anim)
                .setPopExitAnim(R.anim.nav_default_pop_exit_anim);
        if ((item.getOrder() & Menu.CATEGORY_SECONDARY) == 0) {
            optionsBuilder.setPopUpTo(findStartDestination(navController.getGraph()).getId(), false);
        }

        final NavAction navAction = navController.getCurrentDestination().getAction(resId);
        if (navAction != null) {
            NavOptions navOptions = navAction.getNavOptions();

            // Note : You can Add *setLaunchSingleTop* and *setPopUpTo* from *navOptions* to *builder*
            if (navOptions.getEnterAnim() != -1) {
                optionsBuilder.setEnterAnim(navOptions.getEnterAnim());
            }
            if (navOptions.getExitAnim() != -1) {
                optionsBuilder.setExitAnim(navOptions.getExitAnim());
            }
            if (navOptions.getPopEnterAnim() != -1) {
                optionsBuilder.setPopEnterAnim(navOptions.getPopEnterAnim());
            }
            if (navOptions.getPopExitAnim() != -1) {
                optionsBuilder.setPopExitAnim(navOptions.getPopExitAnim());
            }

            Bundle navActionArgs = navAction.getDefaultArguments();
            if (navActionArgs != null) {
                args = new Bundle();
                args.putAll(navActionArgs);
            }
        }

        options = optionsBuilder.build();

        try {
            //TODO provide proper API instead of using Exceptions as Control-Flow.
            navController.navigate(resId, args, options);
            return true;
        } catch (IllegalArgumentException e) {
            return false;
        }
    }

    public static void setupWithNavController(
            @NonNull final BottomNavigationView bottomNavigationView,
            @NonNull final NavController navController) {
        bottomNavigationView.setOnNavigationItemSelectedListener(
                new BottomNavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                        return onNavDestinationSelected(item, navController);
                    }
                });
        final WeakReference<BottomNavigationView> weakReference =
                new WeakReference<>(bottomNavigationView);
        navController.addOnDestinationChangedListener(
                new NavController.OnDestinationChangedListener() {
                    @Override
                    public void onDestinationChanged(@NonNull NavController controller,
                                                     @NonNull NavDestination destination, @Nullable Bundle arguments) {
                        BottomNavigationView view = weakReference.get();
                        if (view == null) {
                            navController.removeOnDestinationChangedListener(this);
                            return;
                        }
                        Menu menu = view.getMenu();
                        for (int h = 0, size = menu.size(); h < size; h++) {
                            MenuItem item = menu.getItem(h);
                            if (matchDestination(destination, item.getItemId())) {
                                item.setChecked(true);
                            }
                        }
                    }
                });
    }

    @SuppressWarnings("WeakerAccess") /* synthetic access */
    static boolean matchDestination(@NonNull NavDestination destination,
                                    @IdRes int destId) {
        NavDestination currentDestination = destination;
        while (currentDestination.getId() != destId && currentDestination.getParent() != null) {
            currentDestination = currentDestination.getParent();
        }
        return currentDestination.getId() == destId;
    }

    @SuppressWarnings("WeakerAccess") /* synthetic access */
    static boolean matchDestinations(@NonNull NavDestination destination,
                                     @NonNull Set<Integer> destinationIds) {
        NavDestination currentDestination = destination;
        do {
            if (destinationIds.contains(currentDestination.getId())) {
                return true;
            }
            currentDestination = currentDestination.getParent();
        } while (currentDestination != null);
        return false;
    }

    @SuppressWarnings("WeakerAccess") /* synthetic access */
    static NavDestination findStartDestination(@NonNull NavGraph graph) {
        NavDestination startDestination = graph;
        while (startDestination instanceof NavGraph) {
            NavGraph parent = (NavGraph) startDestination;
            startDestination = parent.findNode(parent.getStartDestination());
        }
        return startDestination;
    }
}

现在,有了它,您需要进行一些更改

MainActivity :之后

BottomNavigationUI.setupWithNavController(bottomNavigationView, navController)
bottomNavigationView.setOnNavigationItemReselectedListener { false }

我们将使用BottomNavigationUI代替,NavigationUI因为它将能够使用自定义anims而不是仅使用默认值。

nav_graph.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"
    android:id="@+id/nav_graph"
    app:startDestination="@id/home_fragment">

    <fragment
        android:id="@+id/home_fragment"
        android:name="com.example.android.navbottomsample.HomeFragment"
        android:label="HomeFragment"
        tools:layout="@layout/fragment_home">
        <action
            app:launchSingleTop="true"
            android:id="@+id/schedule_fragment"
            app:destination="@id/schedule_fragment"
            app:enterAnim="@anim/slide_in_right"
            app:exitAnim="@anim/slide_out_left"
            app:popEnterAnim="@anim/slide_in_left"
            app:popExitAnim="@anim/slide_out_right"
            app:popUpTo="@+id/home_fragment" />
    </fragment>
    <fragment
        android:id="@+id/schedule_fragment"
        android:name="com.example.android.navbottomsample.ScheduleFragment"
        android:label="ScheduleFragment"
        tools:layout="@layout/fragment_schedule">
        <action
            android:id="@+id/home_fragment"
            app:destination="@id/home_fragment"
            app:enterAnim="@anim/slide_in_left"
            app:exitAnim="@anim/slide_out_right"
            app:popEnterAnim="@anim/slide_in_right"
            app:popExitAnim="@anim/slide_out_left"
            app:popUpTo="@+id/home_fragment" />
    </fragment>
</navigation>

所以你不必比较代码,action_id现在翻转了。您还有2 个动作,因为我们将需要它action_id。现在action_id交换的全部意义在于我们需要action_id匹配destination_id,fragment_idmenu_item_id

我也改了app:popUpTo。当您自己尝试时,这将是最合理的。您希望将两个片段都popUpTo放在. 所以,一旦你在,你就不想再往前走了。而一旦你在,你想回到。但是,我建议您使用或因为它们动态指定(当您有超过 2 个底部导航选项卡时,这将是最有用的)home_fragmentbackStackhome_fragmentschedule_fragmenthome_fragmentBottomNavigationUINavigationUIpopUpTo

我已经在您与我共享的项目上尝试了此解决方案,并且它完美无缺。享受 :)


其他解决方案

您可以设置自定义setOnNavigationItemSelectedListener以执行您需要的操作(使用 xml 中指定的自定义动画)

现在,在您的代码(您与我共享的代码)中,您已经创建了一种解决方法,如下所示:

bottomNavigationView.setOnNavigationItemSelectedListener {
    when (it.itemId) {
        R.id.schedule_fragment -> navController.navigate(R.id.home_fragment)
        else -> navController.popBackStack()
    }
    true
}

您可以选择保留它,或执行以下操作(使用更新的nav_graph.xml

bottomNavigationView.setOnNavigationItemSelectedListener {
    navController.navigate(it.itemId)
    true
}

但是,您不应该忘记将其更改nav_graph.xml为新的。


第一次尝试

好的,所以如果你检查NavigationUI AndroidDocs,你会注意到以下内容:

  1. setupWithNavController

    设置 aBottomNavigationView与 a 一起使用NavController这将onNavDestinationSelected(MenuItem, NavController)在选择菜单项时调用。BottomNavigationView目的地更改时,将自动更新所选项目。

  2. onNavDestinationSelected

    尝试导航到NavDestination与给定的关联MenuItem。这MenuItem应该是通过此类中的帮助方法之一添加的。 重要的是,它假定menu item id匹配有效action id或被destination id导航到。

第一次尝试没有解决问题。默认动画仍然播放,而不是在 action 中指定的动画

于 2020-01-20T21:26:51.237 回答