JetPack学习笔记之Navigation(二)
JetPack引入了NavigationUI组件,使得APP Bar中的按钮和菜单可以和导航图中的页面关联起来。比如上文中的例子中,不是通过按钮,而是想通过菜单跳转到第二个Fragment,可采用如下方式。
1、创建menu.xml文件,并将item的id设置为第二个Fragment的id。
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/secondFragment"
android:title="跳转"/>
</menu>
2、在Activity中初始化菜单,并相应菜单的点击事件,完整代码如下:
public class NavigationActivity extends AppCompatActivity {
private AppBarConfiguration appBarConfiguration;
private NavController navController;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
navController = Navigation.findNavController(this,R.id.nav_host_fragment);
appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph()).build();
NavigationUI.setupActionBarWithNavController(this,navController,appBarConfiguration);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
return NavigationUI.onNavDestinationSelected(item,navController) || super.onOptionsItemSelected(item);
}
@Override
public boolean onSupportNavigateUp() {
return NavigationUI.navigateUp(navController,appBarConfiguration) || super.onSupportNavigateUp();
}
}