我试图使用Intent,但它在导航抽屉中不起作用。它仅适用于原生Menuitem(3分),但我想在导航抽屉中使用它。
任何人都可以帮助我吗?
@Override
public boolean onOptionsItemSelected(MenuItem item){
if (mToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.menu_one) {
Intent intent = new Intent(this, Activity1.class);
startActivity(intent);
} else if (id == R.id.menu_two) {
Intent intent = new Intent(this, Activity2.class);
startActivity(intent);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawerLayout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
答案 0 :(得分:-1)
不使用 this
关键字,而是使用getApplicationContext()
Intent intent = new Intent(getApplicationContext(), Activity2.class);
startActivity(intent);
或
startActivity(new Intent(Activity1.class, Activity2.class);
答案 1 :(得分:-1)
检查
public class SetNavigationView {
-----------------------------
-----------------------------
private Context mcontext;
-----------------------------
-----------------------------
public SetNavigationView(final Activity activity, final NavigationView navigationView, final DrawerLayout drawer) {
this.mcontext = activity.getApplicationContext();
-----------------------------
-----------------------------
/*TODO add menu item selection */
NavigationView.OnNavigationItemSelectedListener item_click_listener = new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
if (id == R.id.nav_home) {
// Handle the home action
Intent intent = new Intent(mcontext, Home.class);
activity.startActivity(intent);
}
-----------------------------
-----------------------------
}
}
navigationView.setNavigationItemSelectedListener(item_click_listener);
}
}
答案 2 :(得分:-1)
这个尝试代码。
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.menu_one) {
startActivity(new Intent(MainActivity.this,Activity1.class));
//MainActivity: Active activity
} else if (id == R.id.menu_two) {
startActivity(new Intent(MainActivity.this,Activity2.class));
//MainActivity: Active activity
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawerLayout);
drawer.closeDrawer(GravityCompat.START);
return true;
}