Fragment相关

Fragment中监听返回键

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//主界面获取焦点,用来监听返回键
private void getFocus() {
View view = getView();
if (view == null) {
return;
}

view.setFocusableInTouchMode(true);
view.requestFocus();
view.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
// 监听到返回按钮点击事件
if (mCbControlSelectAll.getVisibility() == View.VISIBLE) {
sync(false);
return true;
}
}
return false;
}
});
}

通过调用 fragment 的 isAdded() 方法,来判断当前的 fragment 是否阵亡。

  • 具体用法参考:com.example.android.architecture.blueprints.todoapp.tasks.TasksContract.isActive();
  • isAdded()文档:Return true if the fragment is currently added to its activity.

How to implement onBackPressed() in Fragments?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public interface OnBackPressedListener {
public void doBack();
}

// create method to set listener in CustomActivity
public void setOnBackPressedListener(OnBackPressedListener onBackPressedListener) {
this.onBackPressedListener = onBackPressedListener;
}

// in override onBackPressed implement something like that
@Override
public void onBackPressed() {
if (onBackPressedListener != null)
onBackPressedListener.doBack();
else
super.onBackPressed();
}

// in your fragment in onCreateView you should add our listener
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
activity = getActivity();
((CustomActivity)activity).setOnBackPressedListener(new OnBackPressedListener(){
@override
public void doBack(){
// do your logic
}
});
return view;
}