在菜单项单击上打开第二个活动

时间:2016-03-13 19:29:23

标签: java android android-activity menu

我一直在寻找一种从菜单项点击中打开辅助活动的方法。经过几次尝试在其他人的帖子中找到我的问题的答案后,我决定提问。我们非常感谢帮助以代码片段的形式快速申请,谢谢:)

@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_gallery) {
        MainFragment fragment = new MainFragment();
        android.support.v4.app.FragmentTransaction fragmentTransaction =
                getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.commit();

        //open gallery
        startActivity(new Intent(MainActivity.this, PhotoGallery.class));
    }

    else if (id == R.id.nav_share) {
        MainFragment fragment = new MainFragment();
        android.support.v4.app.FragmentTransaction fragmentTransaction =
                getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container,fragment);
        fragmentTransaction.commit();
    }
    else if (id == R.id.nav_msg)
    {
        MainFragment fragment = new MainFragment();
        android.support.v4.app.FragmentTransaction fragmentTransaction =
                getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container,fragment);
        fragmentTransaction.commit();
    }
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

1 个答案:

答案 0 :(得分:0)

@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_gallery) {
        //open gallery

        Intent galleryIntent = new Intent(YourCurrentActivity.this, PhotoActivity.class);
        //if you need to pass data: 
        Bundle mBundle = new Bundle();
        mBundle.putString("myKey", "opengalleryclicked");
        galleryIntent.putExtras(mBundle); 
        startActivity(galleryIntent);
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

传递的数据可以通过以下方式在您的第二项活动中收到:

String value = getIntent().getExtras().getString("myKey");