1、创建自定义接口类
public interface BackHandleInterface {
void onSelectedFragment(BackHandleFragment backHandleFragment);
}
2、创建一个自定义Fragment类
public abstract class BackHandleFragmentextends BaseFragment{
private BackHandleInterfacebackHandleInterface;
/**
* 所有继承BackHandledFragment的子类都将在这个方法中实现物理Back键按下后的逻辑
* FragmentActivity捕捉到物理返回键点击事件后会首先询问Fragment是否消费该事件
* 如果没有Fragment消息时FragmentActivity自己才会消费该事件
*/
public abstract boolean onBackPressed();
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(getActivity()instanceof BackHandleInterface){
this.backHandleInterface = (BackHandleInterface)getActivity();
}else{
throw new ClassCastException("Hosting Activity must implement BackHandledInterface");
}
}
@Override
public void onStart() {
super.onStart();
backHandleInterface.onSelectedFragment(this);
}
}
3、在fragment的容器Activity中
1)声明变量属性
private BackHandleFragmentbackHandleFragment;
2)activity实现接口(implements BackHandleInterface),重写回调方法
@Override
public void onSelectedFragment(BackHandleFragment backHandleFragment) {
this.backHandleFragment = backHandleFragment;
}
3)重写onKeyDown()方法
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//if判断里面就调用了来自Fragment的onBackPressed()
//一样!!,如果onBackPressed是返回false,就会进入条件内进行默认的操作
if(backHandleFragment ==null || !backHandleFragment.onBackPressed()){
if(getSupportFragmentManager().getBackStackEntryCount() ==0){
/**
* 按返回键直接返回桌面,监听返回键,防止按了音量键也返回桌面
*/
if (keyCode == KeyEvent.KEYCODE_BACK){
Intent intent =new Intent(Intent.ACTION_MAIN);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
return true;
}
}
}
return super.onKeyDown(keyCode, event);
}
4、fragment继承自定义fragemnt,重写回调方法onBackPressed()
tip:因为我的项目中fragment是包含整个webview,需求是点击返回后,webview如果可以返回上一个页面就返回上一个页面
@Override
public boolean onBackPressed() {
if (webView.canGoBack()){
webView.goBack();
return true;
}else {
return false;
}
}