[英]How to add a click listener to Menu Item in Kotlin
我想創建一個底部導航欄。 我使用android BottomNavigationView來創建UI,但我不知道如何在菜單中的項目中添加OnClick監聽器。
我在谷歌搜索並找到了一些文章,但他們都使用了工具欄元素。 我不知道如何添加它以及它正在做什么。
這是我在主要活動中包含的導航條形碼
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:design="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout android:layout_width="match_parent" android:id="@+id/bottom_nav"
android:background="@drawable/gradient_theme"
android:layout_height="wrap_content" android:layout_gravity="bottom">
<android.support.design.widget.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/white"
android:id="@+id/menuBar"
design:menu="@menu/menu_bar"
design:itemIconTint="@android:color/darker_gray"/>
</RelativeLayout>
</FrameLayout>
這是我想要設置監聽器的MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
beautifyLayout(this, window)
setSupportActionBar(toolbar)
testButton.setOnClickListener {
val intent= Intent(this,AccountActivity::class.java)
finish()
startActivity(intent)
}
}
}
這是menu_bar.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/btn1" android:title="" android:icon="@drawable/ic_feed"/>
<item android:id="@+id/btn2" android:title="" android:icon="@drawable/ic_chat_bubble_black_24dp"/>
<item android:id="@+id/btn3" android:title="" android:icon="@drawable/ic_search_black_24dp"/>
<item android:id="@+id/btn4" android:title="" android:icon="@drawable/ic_menu_black_24dp" />
</menu>
用戶界面工作得很好,只需要一些聽眾。 我希望盡可能只使用BottomNavigationView。
這是你設置監聽器的方式:
val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.btn1 -> {
// put your code here
return@OnNavigationItemSelectedListener true
}
R.id.btn2 -> {
// put your code here
return@OnNavigationItemSelectedListener true
}
R.id.btn3 -> {
// put your code here
return@OnNavigationItemSelectedListener true
}
R.id.btn4 -> {
// put your code here
return@OnNavigationItemSelectedListener true
}
}
false
}
menuBar.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
如果menuBar
在您的活動布局中,則不需要初始化。
如果沒有,則必須使用findViewById()
進行初始化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.