Activity 比较容易监听物理键返回事件(onBackPressed);Fragment却不能
假设一个FragmentActivity包含3个Fragment,用户一般期望在返回时,逐层返回到FragmentActivity,当然我们可以将每个Fragment对应的Transaction放到BackStack当中,但是如果每个Fragment有对返回事件的特殊消费,如何优雅的实现了?
- 首先创建一个抽象类BaseHandleFragment,该类有一个抽象方法onBackPressed方法,所有子Fragment继承于他,实现该方法处理各自对Back事件的消费逻辑,该方法返回一个布尔值,宿主FragmentActivity将会根据该方法返回值判断子Fragment是否有消费Back事件
public abstract class BackHandledFragment extends Fragment {
protected BackHandledInterface mBackHandledInterface;
/**
* 所有继承BackHandledFragment的子类都将在这个方法中实现物理Back键按下后的逻辑
* FragmentActivity捕捉到物理返回键点击事件后会首先询问Fragment是否消费该事件
* 如果没有Fragment消息时FragmentActivity自己才会消费该事件
*/
protected abstract boolean onBackPressed();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(!(getActivity() instanceof BackHandledInterface)){
throw new ClassCastException("Hosting Activity must implement BackHandledInterface");
}else{
this.mBackHandledInterface = (BackHandledInterface)getActivity();
}
}
@Override
public void onStart() {
super.onStart();
//告诉FragmentActivity,当前Fragment在栈顶
mBackHandledInterface.setSelectedFragment(this);
}
}
2.宿主Activity将会保存一份当前Fragment的引用,当用户按下Back键时,Activity会通过上述1中onBackPressed的返回值,判断该Fragment是否有消费该事件,没有才会自己消费
3.宿主FragmentActivity需要继承BackHandleInterface,子Fragment会通过该接口告诉宿主Activity自己是当前屏幕可见的Fragment
public interface BackHandledInterface {
public abstract void setSelectedFragment(BackHandledFragment selectedFragment);
}
public class MainActivity extends FragmentActivity implements BackHandledInterface{
private BackHandledFragment mBackHandedFragment;
private boolean hadIntercept;
@Override
public void setSelectedFragment(BackHandledFragment selectedFragment) {
this.mBackHandedFragment = selectedFragment;
}
@Override
public void onBackPressed() {
if(mBackHandedFragment == null || !mBackHandedFragment.onBackPressed()){
if(getSupportFragmentManager().getBackStackEntryCount() == 0){
super.onBackPressed();
}else{
getSupportFragmentManager().popBackStack();
}
}
}
}
总结一下:
每个Fragment的onCreate方法中,会判断宿主Activity是否实现了上述3中所说的接口,在Fragment的onStart方法中,通过Fragment 获取Activity 引用,然后调用该Activity实现的接口方法告知宿主FragmentActivity自己是当前屏幕可见的Fragment,宿主Activity就可以在onBackPressed 方法中对Back事件进行判断处理了