Set selected item in Android BottomNavigationView

前端 未结 21 2360
谎友^
谎友^ 2020-11-27 14:16

I am using the new android.support.design.widget.BottomNavigationView from the support library. How can I set the current selection from code? I realized, that

21条回答
  •  情歌与酒
    2020-11-27 15:05

    IF YOU NEED TO DYNAMICALLY PASS FRAGMENT ARGUMENTS DO THIS

    There are plenty of (mostly repeated or outdated) answers here but none of them handles a very common need: dynamically passing different arguments to the Fragment loaded into a tab.

    You can't dynamically pass different arguments to the loaded Fragment by using setSelectedItemId(R.id.second_tab), which ends up calling the static OnNavigationItemSelectedListener. To overcome this limitation I've ended up doing this in my MainActivity that contains the tabs:

    fun loadArticleTab(articleId: String) {
        bottomNavigationView.menu.findItem(R.id.tab_article).isChecked = true // use setChecked() in Java
        supportFragmentManager
            .beginTransaction()
            .replace(R.id.main_fragment_container, ArticleFragment.newInstance(articleId))
            .commit()
    }
    

    The ArticleFragment.newInstance() method is implemented as usual:

    private const val ARG_ARTICLE_ID = "ARG_ARTICLE_ID"
    
    class ArticleFragment : Fragment() {
    
        companion object {
            /**
             * @return An [ArticleFragment] that shows the article with the given ID.
             */
            fun newInstance(articleId: String): ArticleFragment {
                val args = Bundle()
                args.putString(ARG_ARTICLE_ID, day)
                val fragment = ArticleFragment()
                fragment.arguments = args
                return fragment
            }
        }
    
    }
    

提交回复
热议问题