Android DialogFragment 与 Dialog [英] Android DialogFragment vs Dialog
问题描述
Google 建议我们使用 DialogFragment
而不是简单的 Dialog
使用 Fragments API
,但是使用孤立的 是荒谬的>DialogFragment
用于简单的 Yes-No 确认消息框.在这种情况下,最佳做法是什么?
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
带有是/否确认按钮.代码不多.
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.
关于在你的片段中处理事件,有多种方法可以做到,但我只是在我的 Fragment
中定义了一个消息 Handler
,将它传递到 DialogFragment
通过其构造函数,然后根据各种点击事件将消息传递回我的片段的处理程序.同样有各种方法可以做到这一点,但以下对我有用.
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();
}
}
编辑
并且由于 Message
是可打包的,您可以将其保存在 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 与 Dialog的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!