Android导航组件如何保存BottomNavigationBar片段状态

时间:2019-10-07 14:25:48

标签: android android-architecture-components android-jetpack android-navigation android-architecture-navigation

我使用了NavigationAdvancedSample中的NavigationExtensions.kt类来实现BottomNavigationBar导航。如下:

 bottomNavigationView = findViewById(R.id.bottom_nav)
        val navGraphIds = listOf(R.navigation.home, R.navigation.category, R.navigation.cart, R.navigation.account, R.navigation.jak)
        // Setup the bottom navigation view with a list of navigation graphs
        val controller = bottomNavigationView?.setupWithNavController(
                navGraphIds = navGraphIds,
                fragmentManager = supportFragmentManager,
                containerId = R.id.nav_host_container,
                intent = intent
        )

        // Whenever the selected controller changes, setup the action bar.
        controller?.observe(this, Observer { navController ->
            setupActionBarWithNavController(navController)
        })
        currentNavController = controlle

我正在尝试保存每次点击的片段状态,但是我不知道该怎么做。 所有类和片段都是用Java编写的,只有主要活动和NavigationExtensions用Kotlin编写。 导航实施:

implementation "androidx.navigation:navigation-fragment:2.2.0-alpha03"
implementation "androidx.navigation:navigation-ui:2.2.0-alpha03"
implementation "androidx.navigation:navigation-fragment-ktx:2.2.0-alpha03"
implementation "androidx.navigation:navigation-ui-ktx:2.2.0-alpha03"

这是我的Fragment onCreateView方法之一:

@Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        mViewModel = ViewModelProviders.of(this).get(HomePageViewModel.class);
        binding = DataBindingUtil.inflate(inflater, R.layout.home_page_fragment, container, false);
        binding.setLifecycleOwner(this);
        mViewModel.init();
        binding.setViewModel(mViewModel);
        setHasOptionsMenu(true);
        ((MainActivity) getActivity()).homeToolbarWithImage();
        ShowMainList();
        binding.swiperefresh.setOnRefreshListener(this);
        return binding.getRoot();
    }

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

您可以使用“ FragmentPagerAdapter”保存diff片段的状态。使用“ FragmentPagerAdapter”添加片段。如果您无法理解Java类,也不必担心。您仍然可以直接在您的kotlin类中使用这些内容。 Kotline提供了互操作性,因此您可以在同一项目中一起使用java和kotiln类。