如何将点击侦听器添加到 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>

用户界面运行良好,只需要一些侦听器。如果可能的话,我希望只使用底部导航视图。

这是您设置侦听器的方式:

    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() 对其进行初始化。

最新更新