如何在抽屉菜单中更改第一个片段 [英] How I can change my first fragment in drawerMenu
问题描述
我遇到了麻烦,必须通过程序设置第一个显示的片段(每次尝试打开抽屉时都必须更改第一个片段),我搜索了很多但无法更改代码.帮帮我.
I'm In trouble and I have to set my first shown fragment by a program ( I have to change the first fragment every time I try to open the drawer), I searched a Lot but I can't change my code. Help me guys.
我的抽屉代码:
public class Maincontant extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maincontant);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_gallery,R.id.nav_home , R.id.nav_slideshow,
R.id.nav_tools, R.id.nav_share, R.id.nav_contact)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);//
NavigationUI.setupActionBarWithNavController(this, navController,mAppBarConfiguration);//
NavigationUI.setupWithNavController(navigationView, navController);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.maincontant, menu);
return true;
}
@Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
}
推荐答案
您可以使用 setNavigationItemSelectedListener
,然后可以像下面这样调用特定的 fragment
:
You can use setNavigationItemSelectedListener
then can call specific fragment
like this following:
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
Log.e("selected","selected---menu---"+menuItem.toString());
if (drawer.isDrawerVisible(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
drawer.openDrawer(GravityCompat.START);
}
if(menuItem.toString().equalsIgnoreCase("Gallery"))
{
navController.navigate(R.id.nav_gallery2);
}
else if(menuItem.toString().equalsIgnoreCase("Home"))
{
navController.navigate(R.id.nav_home);
}
else
{
navController.navigate(R.id.nav_slideshow);
}
return true;
}
});
如果您使用的是 NavigationGraph
,则必须在其中指定 fragment
. navController.navigate(R.id.nav_gallery2);
,我已在 NavigationGraph
上指定了此 fragment
,但未在 DrawerMenu 上指定代码>.
If you are using NavigationGraph
then you will have to specify the fragment
there. navController.navigate(R.id.nav_gallery2);
, I have specified this fragment
on NavigationGraph
, But not on DrawerMenu
.
这篇关于如何在抽屉菜单中更改第一个片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!