android - 如何在对象列表上建模导航抽屉菜单?
问题描述
我的 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约定在这里使用不同的模式?
解决方案
我的解决方案是使用 aRecyclerView
或ListView
代替 a NavigationView
。
推荐阅读
- ios - 如何制作像这样粘在顶部的分段控制器?
- php - 将所有get参数传递给另一个链接php
- macos - Xamarin.Mac PdfView 性能问题
- python - 是否可以在 python 中定义一个新的数学运算符?
- mongodb - 通过数组内部文档的 id 更新数组中的文档,但是如果该 id 的文档在数组中不存在,则在 mongodb 中创建一个具有该 ID 的文档
- python - 无法从 pipenv virtualenv 导入 pyspark,因为它找不到 py4j
- python - 如何从 Instagram 中提取数据?
- django - drf-yasg 如何在外面显示 api 描述?
- json - 怎么修
在 WSO2 中 - sql - 带光标的 SSRS 订阅