最新更新 - 2019 年 4 月 25 日
新版本androidx.activity 版本。1.0.0-alpha07带来了一些变化
android官方指南中的更多解释:提供自定义后退导航
例子:
public class MyFragment extends Fragment {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// This callback will only be called when MyFragment is at least Started.
OnBackPressedCallback callback = new OnBackPressedCallback(true /* enabled by default */) {
@Override
public void handleOnBackPressed() {
// Handle the back button event
}
};
requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);
// The callback can be enabled or disabled here or in handleOnBackPressed()
}
...
}
旧更新
UPD:2019 年 4 月 3 日
现在它简化了。更多信息在这里
例子:
requireActivity().getOnBackPressedDispatcher().addCallback(getViewLifecycleOwner(), this);
@Override
public boolean handleOnBackPressed() {
//Do your job here
//use next line if you just need navigate up
//NavHostFragment.findNavController(this).navigateUp();
//Log.e(getClass().getSimpleName(), "handleOnBackPressed");
return true;
}
已弃用(自 2019 年 4 月 3 日版本 1.0.0-alpha06 起):
既然这样,它就可以在您的片段中使用JetPack 实现来实现OnBackPressedCallback
并将其添加到活动中:
getActivity().addOnBackPressedCallback(getViewLifecycleOwner(),this);
您的片段应如下所示:
public MyFragment extends Fragment implements OnBackPressedCallback {
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getActivity().addOnBackPressedCallback(getViewLifecycleOwner(),this);
}
@Override
public boolean handleOnBackPressed() {
//Do your job here
//use next line if you just need navigate up
//NavHostFragment.findNavController(this).navigateUp();
//Log.e(getClass().getSimpleName(), "handleOnBackPressed");
return true;
}
@Override
public void onDestroyView() {
super.onDestroyView();
getActivity().removeOnBackPressedCallback(this);
}
}
UPD:
您的活动应该扩展AppCompatActivity
或FragmentActivity
在 Gradle 文件中:
implementation 'androidx.appcompat:appcompat:{lastVersion}'