2016-11-13 9 views
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); 
} 

引き出しが正しく開閉されますが、ログを表示するなど、アイテムをクリックしたときに何かを行う方法がわかりません。

誰でも知っていますか?

おかげ

答えて

1

利用onNavigationItemSelected()メソッドは、ナビゲーションドロワーの項目をクリックして処理します。以下のコードを参照してください。

private NavigationView mNavigationView; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) 
    { 
    // ... 
    mNavigationView = (NavigationView) findViewById(R.id.nav_view); 
    mNavigationView.setNavigationItemSelectedListener(this);// you need to set Listener. 
    } 




@SuppressWarnings("StatementWithEmptyBody") 
@Override 
public boolean onNavigationItemSelected(MenuItem item) 
{ 
    // mDrawer.closeDrawer(GravityCompat.START); 
    switch (item.getItemId()) { 
     case R.id.item1: { 

     } 
     break; 
     case R.id.item2: { 

     } 
     break; 
     case R.id.item3: { 

     } 
     break; 

    } 
    return true; 
} 
+1

なぜ私はうまくいきませんか?リスナーsetNavigationItemSelectedListenerを設定することを忘れてしまったと思います。今私は上記のコードを更新しました。 –

+0

これを試してみます。私はあなたに5分で知らせます。ありがとう! – Sergio

+1

kkなので、setNavigationItemSelectedListenerのListenerを設定するのは忘れてしまいます。問題はない、その仕事は今。このコードは私のために働く。 –

関連する問題