[英]Open activity from Menu item
I'm trying to use Intent, but it does not work in Navigation Drawer. 我正在尝试使用Intent,但它在Navigation Drawer中不起作用。 It worked only on the native Menuitem (3 points), but I want to use it in Navigation Drawer.
它仅适用于本机Menuitem(3分),但我想在导航抽屉中使用它。
can anybody help me? 有谁能够帮助我?
@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;
}
Instead of using this
keyword , use getApplicationContext()
代替使用
this
关键字,使用getApplicationContext()
Intent intent = new Intent(getApplicationContext(), Activity2.class);
startActivity(intent);
or 要么
startActivity(new Intent(Activity1.class, Activity2.class);
Check this 检查一下
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);
}
}
This try code. 此尝试代码。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.