如何在Android的NavigationView上向项目添加点击事件 [英] How to add click event to item on NavigationView of Android
本文介绍了如何在Android的NavigationView上向项目添加点击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在Android项目中实现侧边栏 NavigationDrawer
.为此,我在 DrawerLayout
中使用了 NavigationView
.为了显示项目,我使用了菜单.我想在该添加的菜单项上添加点击事件.
I am trying to implement Sidebar NavigationDrawer
in my Android project.
To do so, I have used NavigationView
in DrawerLayout
. To show items I used menu.
I want to add click event on that added menu items.
参考代码:在导航菜单中-
Code for reference: In navigation menu -
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/nav_account" android:title="My Account"/>
<item android:id="@+id/nav_settings" android:title="Settings"/>
<item android:id="@+id/nav_layout" android:title="Log Out"/>
</menu>
在视图中:
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:menu="@menu/navigation_menu"
android:layout_gravity="start" />
推荐答案
-
在您的活动"中实现侦听器:
Implement the listener in your Activity:
public class HomeActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener
Activity的onCreate中的
setNavigationItemSelectedListener
setNavigationItemSelectedListener in onCreate of Activity
NavigationView mNavigationView = (NavigationView) findViewById(R.id.account_navigation_view);
if (mNavigationView != null) {
mNavigationView.setNavigationItemSelectedListener(this);
}
覆盖方法
Override the method
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_account) {
// DO your stuff
}
}
这篇关于如何在Android的NavigationView上向项目添加点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文