Navigation 结合Fragment使用
首先创建Navigation的资源文件,即绘制跳转路径的文件,创建方法如下:
创建Navigation资源文件.png 创建navgation.png
需要添加依赖库
navgation_hint.png为两个Fragment添加跳转逻辑并在Activity中添加NavgationHost
为页面添加跳转逻辑.png给首页页面按钮添加点击事件
btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
NavController controller = Navigation.findNavController(v);
//跳转到详情面页
controller.navigate(R.id.action_homeFragment3_to_detailFragment3);
}
});
给详情页面按钮添加点击事件
Button btn = getView().findViewById(R.id.button);
//跳转到首页
btn.setOnClickListener(
Navigation.createNavigateOnClickListener(R.id.action_detailFragment3_to_homeFragment3)
);
在Activity中设置ActionBar使用Navigation导航返回上一层
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//fragment2为activity_main中NavHostFragment的id
NavController navController = Navigation.findNavController(this,R.id.fragment2);
//设置ActionBar使用Navigation导航
NavigationUI.setupActionBarWithNavController(this, navController);
}
@Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this,R.id.fragment2);
return navController.navigateUp(); //返回上一层
//return super.onSupportNavigateUp();
}
https://github.com/LongLongLongLongLongLongLongLongLong/NavigationDemo1.git
网友评论