2017-11-11 77 views
2

我在Kotlin中創建了抽屜菜單,我想使用這個菜單項。在java中,我打電話給onNavigationItemSelected方法,但是當我想在Kotlin中使用它時,它不會出現。這裏是我的代碼:Android 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它使烤麪包。非常感謝您的幫助!

回答

2

你可以給你的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 
    } 
} 
+0

謝謝你的答案,但我怎麼能開始新的與此有關的活動? –

+0

您可以在處理導航項目點擊的塊內編寫任何代碼 - 只需在其中寫入啓動新「活動」的代碼即可。如果你不知道怎麼做,你應該首先看看Android上的一些初學者教程。 – zsmb13