最早是在返回回调中监听
override fun onBackPressed() {
super.onBackPressed()
L.d(TAG) { "onBackPressed: " }
}
这样的做法不好标准准好,经常需要来一个写一个,这样很麻烦,因此可以这样
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState) requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner) {
L.d(TAG) { "onActivityCreated: onBackPressed ${this.javaClass.simpleName}" }
FragmentUtils.remove(this@TestFragment)
}
}
以上在Fragment的onActivityCreated加入拦截就不用Acitvity来管理,而且可以正常的Fragment的基来中,来看下它的执行顺序:
2020-10-26 07:55:06.084 18359-18359/app.worson.timewallet D/LogX#TestFragment@{EditTextListFragment} (TestFragment.kt:38): onActivityCreated: onBackPressed
2020-10-26 07:55:06.086 18359-18359/app.worson.timewallet D/LogX#MainActivity (MainActivity.kt:123): onBackPressed:
这说明跟最早的之法是一样的,不过这得要用ComponentActivity才行,看到它的实现如下:
@MainThread
public void onBackPressed() {
mOnBackPressedDispatcher.onBackPressed();
}