android-fragments 片段-“在向后导航时”与“后退”按钮的方式不同

0s7z1bwu  于 2022-11-14  发布在  Android
关注(0)|答案(1)|浏览(155)

我写的安卓应用程序,使用片段。
向上或向后导航有两种主要方式。
picture of the screen
1.第一种是使用导航栏上的箭头(图中用数字1标记)
1.第二次使用系统后退按钮(标有数字2)
我写道:

override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
...
        requireActivity().onBackPressedDispatcher.addCallback(this) {
                findNavController().navigate(R.id.action_updateFragment_to_listFragment)
...    
}

而且它工作得很好,但只适用于系统后退按钮(2)。

如何覆盖单击导航栏(1)中的后退箭头所导致的操作?

谢谢!2!3!

xnifntxz

xnifntxz1#

好吧,我来处理。

override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if(item.itemId == android.R.id.home) {
            Toast.makeText(requireContext(), "the answer", Toast.LENGTH_SHORT).show()
        }
        return super.onOptionsItemSelected(item)
    }

我希望这篇文章能在未来对某些人有所帮助。

相关问题