我在Kotlin制作抽屉菜单,我想使用这个菜单项。在java中我调用了onNavigationItemSelected
方法但是当我想在Kotlin中使用它时它并没有出现。这是我的代码:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/drawerLayout"
tools:context="com.example.zamknijryjx.liobrus.UserActivity">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/imie"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="40dp"
android:text="Imie"
android:textSize="50sp"
android:textColor="@color/black"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:menu="@menu/navigation_menu"
android:layout_gravity="start"
app:headerLayout="@layout/navigation_header">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
以下是navigation_menu.xml
:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/nav_home"
android:title="Home"/>
<item android:id="@+id/nav_sprawdziany"
android:title="Sprawdziany"/>
<item android:id="@+id/nav_prace"
android:title="Prace klasowe"/>
</menu>
我的活动中的代码:
mToggle = ActionBarDrawerToggle(this, drawerLayout, R.string.open, R.string.close)
drawerLayout.addDrawerListener(mToggle!!)
mToggle!!.syncState()
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
if (mToggle!!.onOptionsItemSelected(item)) {
return true
}
return super.onOptionsItemSelected(item)
}
所以我想做这样的事情:当用户单击带有id的菜单项时,例如nav_home
,它就会生成吐司。非常感谢您的帮助!
答案 0 :(得分:6)
您可以在布局文件中提供NavigationView
个ID:
<android.support.design.widget.NavigationView
android:id="@+id/navigationView"
... >
</android.support.design.widget.NavigationView>
然后在UserActivity
中添加一个监听器:
navigationView.setNavigationItemSelectedListener {
when (it.itemId) {
R.id.nav_home -> {
// handle click
true
}
else -> false
}
}
答案 1 :(得分:1)
@ zsmb13的代码可以工作,但是以某种方式与关闭抽屉有关。
我按如下所示编辑了代码,并且效果很好
navigationView.setNavigationItemSelectedListener { menuItem ->
when (menuItem.itemId) {
R.id.nav_gallery -> {
handleGalleryOption()
if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
drawer_layout.closeDrawer(GravityCompat.START)
}
true
}
else -> {
if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
drawer_layout.closeDrawer(GravityCompat.START)
}
false
}
}
}