DialogFragment 和后退按钮

发布于 2024-12-07 07:40:18 字数 696 浏览 0 评论 0 原文

是否有可能拦截DialogFragment中的按键按钮?抱歉这个天真的问题..我的 FragmentActivityonBackPressed 从未被调用过。

预先感谢

    if (imageFile.exists()) {
            ShowPicDialog newFragment = ShowPicDialog.newInstance();
            FragmentTransaction ft = manager.beginTransaction();
            Fragment prev = manager.findFragmentByTag("picDialog");
            if (prev != null) {
                ft.remove(prev);
            }

            ft.addToBackStack("picDialog");
            newFragment.getArguments().putString("path", imageFile.getAbsolutePath());
            newFragment.show(ft, "picDialog");
        }

抱歉,我添加了用于显示对话框的代码片段。

Is there any possibility to intercept the key button in DialogFragment? sorry for the naive question.. the onBackPressed of my FragmentActivity is never called.

thanks in advance

    if (imageFile.exists()) {
            ShowPicDialog newFragment = ShowPicDialog.newInstance();
            FragmentTransaction ft = manager.beginTransaction();
            Fragment prev = manager.findFragmentByTag("picDialog");
            if (prev != null) {
                ft.remove(prev);
            }

            ft.addToBackStack("picDialog");
            newFragment.getArguments().putString("path", imageFile.getAbsolutePath());
            newFragment.show(ft, "picDialog");
        }

sorry I added the snip of code I use to show the dialog.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

迷离° 2024-12-14 07:40:18

很难确定问题是什么,因为您还没有发布任何代码。但我的第一个猜测是,您没有通过调用用于将片段添加到活动。

Android 文档页面中有一些示例,提供了 在 Activity 中使用 DialogFragment 的好模式

由于您正在显示一个对话框,因此创建的对话框将接收按键事件,而不是父活动。因此,在创建 Dialog 的片段时设置一个 Dialog.OnKeyListener,并在 Dialog 上调用 setCancelable(false) 以防止后退键被按下。驳回它。然后,您可以在 OnKeyListeneronkey 方法中处理后退键。

It's hard to say for sure what the issue is, since you haven't posted any code. But my first guess is that you haven't added the DialogFragment to the back stack by calling the addToBackStack method of the FragmentTransaction that you're using to add your fragment to the activity.

There are examples right in the Android documentation pages that give examples of a good pattern for using a DialogFragment in your Activity.

Since you are displaying a Dialog, the created Dialog will receive the key events, not the parent Activity. So, set a Dialog.OnKeyListener when you create the Dialog's fragment, and call setCancelable(false) on the Dialog to prevent the back key from dismissing it. You can then handle the back key in your OnKeyListener's onkey method.

醉殇 2024-12-14 07:40:18

使用后退按钮处理 DialogFragment 的最佳方法:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    return new Dialog(getActivity(), getTheme()){
        @Override
        public void onBackPressed() {
            // On backpress, do your stuff here.
        }
    };
}

Best way to Handle DialogFragment with back button:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    return new Dialog(getActivity(), getTheme()){
        @Override
        public void onBackPressed() {
            // On backpress, do your stuff here.
        }
    };
}
傲世九天 2024-12-14 07:40:18

如果您不使用构建器模式,Rahul Pundhir 的答案非常有效。如果您在对话框中使用 Builder 模式,则可以这样做:

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        AlertDialog alertDialog = new AlertDialog.Builder(getContext())
                .setTitle(...)
                .setPositiveButton(...)
                .setNegativeButton(...)
                .setMessage(...)
                .create();

        alertDialog.setOnKeyListener((dialog, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_BACK 
                && event.getAction() == KeyEvent.ACTION_UP) {
                // TODO do the "back pressed" work here
                return true;
            }
            return false;
        });

        return alertDialog;
    }

这通过模仿系统首先如何调用 onBackPressed() 来实现(忽略对 ACTION_UP 的跟踪和侦听)。请参阅 Dialog 上的来源

Rahul Pundhir's answer works great if you aren't using the builder pattern. If you are using the Builder pattern on your dialog you can instead do this:

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        AlertDialog alertDialog = new AlertDialog.Builder(getContext())
                .setTitle(...)
                .setPositiveButton(...)
                .setNegativeButton(...)
                .setMessage(...)
                .create();

        alertDialog.setOnKeyListener((dialog, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_BACK 
                && event.getAction() == KeyEvent.ACTION_UP) {
                // TODO do the "back pressed" work here
                return true;
            }
            return false;
        });

        return alertDialog;
    }

This works by mimicking how the system calls onBackPressed() in the first place (ignoring the tracking and listening for ACTION_UP). See the source on Dialog

意犹 2024-12-14 07:40:18

您可以将它用于 Dialog/ComponentDialog 和 BottomSheetDialog,
只需根据您的对话框类型更改投射的对话框

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
       return super.onCreateDialog(savedInstanceState).also { dialog ->
        //change the ComponentDialog with your type of dialog
        (dialog as ComponentDialog).onBackPressedDispatcher.addCallback(this, object : 
            OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                // your code
            }
        })
    }
}

you can use it for Dialog/ComponentDialog and BottomSheetDialog,
just change the casted dialog with your type of dialog

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
       return super.onCreateDialog(savedInstanceState).also { dialog ->
        //change the ComponentDialog with your type of dialog
        (dialog as ComponentDialog).onBackPressedDispatcher.addCallback(this, object : 
            OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                // your code
            }
        })
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文