0
我有這樣的菜單佈局 「navigation_menu.xml」:抽屜式導航,傾聽項目單擊事件
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/item1"
android:title="@string/item1"/>
<item
android:id="@+id/item2"
android:title="@string/item2"/>
<item
android:id="@+id/item3"
android:title="@string/item3"/>
</menu>
我的主要活動佈局 「activity_main.xml中」 是這樣的:
<android.support.v4.widget.DrawerLayout
android:id="@+id/drawer_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".MainActivity">
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:menu="@menu/navigation_menu"
android:layout_gravity="start">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
這是我初始化抽屜的主要活動的Java代碼:
private DrawerLayout drawer_layout;
private ActionBarDrawerToggle toggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
drawer_layout = (DrawerLayout)findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(this, drawer_layout, R
.string.open_drawer, R.string.close_drawer);
drawer_layout.addDrawerListener(toggle);
toggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// ...
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (toggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
抽屜正確打開和關閉,但是我不知道如何做點什麼,當一個項目被點擊,例如顯示日誌。
有誰知道嗎?
感謝
我可以知道爲什麼不工作?我想你忘記設置監聽器setNavigationItemSelectedListener。現在我更新了我的代碼,見上文。 –
好的,我會試試這個。我在5分鐘內通知你。謝謝! – Sergio
kk,所以你忘了爲setNavigationItemSelectedListener設置監聽器。沒問題,現在的工作。這段代碼適合我。 –