Android的DialogFragment VS对话 [英] Android DialogFragment vs Dialog

查看:137
本文介绍了Android的DialogFragment VS对话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谷歌建议我们使用 DialogFragment ,而不是一个简单的对话框通过使用片段API ,但它是荒谬的,使用一个孤立的 DialogFragment 一个简单的是,没有确认消息框。什么是在这种情况下,最好的做法是什么?

Google recommends that we use DialogFragment instead of a simple Dialog by using Fragments API, but it is absurd to use an isolated DialogFragment for a simple Yes-No confirmation message box. What is the best practice in this case?

推荐答案

是的,使用 DialogFragment onCreateDialog 你可以简单地使用AlertDialog建设者反正创建一个简单的 AlertDialog 是/否确认按钮。不是很code在所有。

Yes, use DialogFragment and in onCreateDialog you can simply use an AlertDialog builder anyway to create a simple AlertDialog with Yes/No confirmation buttons. Not very much code at all.

至于处理事件的片段也将这样做的各种方式,但我只是定义了一个消息处理程序在我的片段,它传递到 DialogFragment 通过它的构造函数,然后传递消息回到我的片段的处理程序approprirate的各种click事件。再次各种这样做的方法,但下面为我工作。

With regards handling events in your fragment there would be various ways of doing it but I simply define a message Handler in my Fragment, pass it into the DialogFragment via its constructor and then pass messages back to my fragment's handler as approprirate on the various click events. Again various ways of doing that but the following works for me.

在对话框中持有消息并创建实例构造函数:

In the dialog hold a message and instantiate it in the constructor:

private Message okMessage;
...
okMessage = handler.obtainMessage(MY_MSG_WHAT, MY_MSG_OK);

实施 onClickListener 在对话框,然后调用处理程序的适当内容:

Implement the onClickListener in your dialog and then call the handler as appropriate:

public void onClick(.....
    if (which == DialogInterface.BUTTON_POSITIVE) {
        final Message toSend = Message.obtain(okMessage);
        toSend.sendToTarget();
    }
 }

修改

和为消息是parcelable你可以将它保存在的onSaveInstanceState ,并恢复它

And as Message is parcelable you can save it out in onSaveInstanceState and restore it

outState.putParcelable("okMessage", okMessage);

然后在的onCreate

if (savedInstanceState != null) {
    okMessage = savedInstanceState.getParcelable("okMessage");
}

这篇关于Android的DialogFragment VS对话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆