Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

kotlin - Dynamic Navigation drawer item in Navigation component architecture Android

I an unable to figure out any possible solution to load drawer items dynamically i.e hide and show particular items as required in Navigation component Architecture Android. Reason being Navigation component architecture forces us to manually inflate drawer by adding items in xml and then add it through code.

Please help if anyone has any idea to do it dynamically like fetching the items from API and populating them.

Note:- Those who don't have idea please do not underrate it or ask for un-necessary code snippet as this fact is a descriptive one and not any code issue.

question from:https://stackoverflow.com/questions/65840997/dynamic-navigation-drawer-item-in-navigation-component-architecture-android

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can build your menu items dynamically.

Fist step - find your navigation view in your Activity

private lateinit var navView: NavigationView
...
navView = findViewById(R.id.nav_view)

Second step - inflate navigation view with items like this

        pages.forEach { page ->
            navView.menu.add(0, page.navId, 0, page.name)
                .apply {
                    setNavItemIcon(this, page.faIcon, page.customIcon)
                    isCheckable = true
                }
        }

        navView.menu.setGroupCheckable(0, true, true)

where pages - list of navigation item models, fetched from db (in your case API) and 'page' is the model of the menu item.

Third step - use setNavigationItemSelectedListener for handling clicks

navView.setNavigationItemSelectedListener {
    onMenuItemSelected(it, pages)
}

Also you maybe you'll need to use navView.menu.clear() to clear menu and inflate it again.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...