首页 > 解决方案 > 如何在对象列表上建模导航抽屉菜单?

问题描述

我的 Android 应用程序有一个导航抽屉。我想通过用户定义的条目填充导航抽屉菜单。用户定义的条目由一个类建模:

data class Location(val name: String, val data: Int)

单击菜单项时,我想调用一个接受Location与单击的菜单项对应的方法。我的最佳想法是将模型保留为List<Location>(此列表最终将从数据库中加载)并将菜单填充到onCreate

class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
    private val toolbar by lazy { findViewById<Toolbar>(R.id.toolbar) }
    private val drawerLayout by lazy { findViewById<DrawerLayout>(R.id.drawerLayout) }
    private val navigationView by lazy { findViewById<NavigationView>(R.id.navigation) }

    private val savedLocations = listOf(Location("foo", 42), Location("bar", 1337))

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Connect the action bar and the navigation drawer
        setSupportActionBar(toolbar)
        val toggle = ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawerOpen, R.string.drawerClose)
        drawerLayout.addDrawerListener(toggle)
        toggle.syncState()

        // Handle clicks in the navigation drawer
        navigationView.setNavigationItemSelectedListener(this)

        // Populate the navigation drawer
        populateDrawer()
    }

    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        // ...
        return true
    }

    fun loadLocation(location: Location) {
        // application logic here
    }

    private fun populateDrawer() {
        for (location in savedLocations) {
            navigationView.menu.add(location.name)
        }
    }
}

onNavigationItemSelected我想做类似的事情

override fun onNavigationItemSelected(item: MenuItem): Boolean {
    val i = item.getIndex();
    loadLocation(savedLocations[i])
    return true
}

但是,它似乎MenuItem不知道它的索引。我可以做的是手动指定itemId这样的:

savedLocations.forEachIndexed { index, location ->
     // set itemId = index for every MenuItem
     navigationView.menu.add(0, index, 0, location.name)
}

哪里i是迭代索引。但这越来越老套了,因为MenuItem.NONE == 0.

有没有更好的解决方案或者Android约定在这里使用不同的模式?

标签: android

解决方案


我的解决方案是使用 aRecyclerViewListView代替 a NavigationView


推荐阅读