Fragment KeyEvent监听

Author Avatar
MXlwq 12月 19, 2016

接口回调

Fragment中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
protected BackHandlerInterface backHandlerInterface;
public interface BackHandlerInterface {
public void setSelectedFragment(Fragment3 backHandledFragment);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//回调函数赋值
if(!(getActivity() instanceof BackHandlerInterface)) {
throw new ClassCastException("Hosting activity must implement BackHandlerInterface");
} else {
backHandlerInterface = (BackHandlerInterface) getActivity();
}
}
@Override
public void onStart() {
super.onStart();
//将自己的实例传出去
backHandlerInterface.setSelectedFragment(this);
}

Activity中回掉

1
2
3
4
5
6
7
8
9
10
11
12
@Override
public void setSelectedFragment(Fragment3 backHandledFragment) {
this.selectedFragment = backHandledFragment;
}
@Override
public void onBackPressed() {
if(selectedFragment == null || !selectedFragment.onBackPressed()) {
super.onBackPressed();
}
}

To be continued