gpt4 book ai didi

android - 如何在 Kotlin 中为菜单项添加点击监听器

转载 作者:行者123 更新时间:2023-11-29 23:06:07 25 4
gpt4 key购买 nike

我想创建一个底部导航栏。我使用 android BottomNavigationView 来创建 UI,但我不知道如何将 OnClick 监听器添加到菜单中的项目。

我在 google 上搜索并找到了一些文章,但所有文章都在使用 Toolbar 元素。我不知道如何添加它以及它在做什么。

这是我在主要 Activity 中包含的导航条码

<?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>

UI 运行良好,只需要一些监听器。我希望尽可能只使用 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 在您的 Activity 布局内,则不需要初始化。
如果不是,则必须使用 findViewById() 对其进行初始化。

关于android - 如何在 Kotlin 中为菜单项添加点击监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56508265/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com