导航菜单按钮可在导航抽屉中单击

时间:2016-11-22 13:39:46

标签: android navigation-drawer

我已经到了创建导航抽屉的地步,我不知道如何从抽屉中点击按钮。

我的MainActivity

public class MainActivity extends AppCompatActivity {

    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mToggle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mDrawerLayout = (DrawerLayout)findViewById(R.id.drawerLayout);
        mToggle = new ActionBarDrawerToggle(this, mDrawerLayout,R.string.open, R.string.close);

        mDrawerLayout.addDrawerListener(mToggle);
        mToggle.syncState();

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if(mToggle.onOptionsItemSelected(item)){

            return true;
        }
        else{
            switch (item.getItemId()){
                case R.id.nav_menu:
                    Toast.makeText(MainActivity.this, "Menu!", Toast.LENGTH_SHORT).show();
                    return true;
                case R.id.nav_setings:
                    Toast.makeText(MainActivity.this, "Settings!", Toast.LENGTH_SHORT).show();
                    return true;
            }
        }

        return super.onOptionsItemSelected(item);
    }
}

请注意onOptionsItemSelected中的switch语句不起作用。

我的菜单xml如下所示:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@+id/nav_menu"
          android:title="My Account"/>
    <item android:id="@+id/nav_setings"
          android:title="Settings"/>
    <item android:id="@+id/nav_logout"
          android:title="Log Out"/>

</menu>

所以,我的问题是如何从抽屉中点击这些项目?

1 个答案:

答案 0 :(得分:2)

假设您DrawerLayout内还有NavigationView,则只需添加OnNavigationItemSelectedListener

NavigationView navigation = (NavigationView) findViewById(R.id.navigation);

navigation.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch(item.getItemId()) {
            case R.id.nav_menu:
                // Handle menu click
                return true;
            case R.id.nav_settings:
                // Handle settings click
                return true;
            case R.id.nav_logout:
                // Handle logout click
                return true;
            default:
                return false;
        }
    }
});