更新时间:2023-02-13 19:16:52
是的,这是我自己一直陷入的常见陷阱.首先让我说,您在 onResume()
中调用 DialogTest.udateListener()
的解决方案似乎完全适合我.
Yeah, this is a common trap I'm falling in all the time myself. First of all let me say that your solution of calling DialogTest.udateListener()
in onResume()
seems to be fully appropriate to me.
另一种方法是使用 ResultReceiver
,它可以序列化为 Parcelable
:
An alternative way would be to use a ResultReceiver
which can be serialized as a Parcelable
:
public class DialogTest extends DialogFragment {
public static DialogTest newInstance(ResultReceiver receiver, int titleId, int messageId) {
DialogTest frag = new DialogTest();
Bundle args = new Bundle();
args.putParcelable("receiver", receiver);
args.putInt("titleId", titleId);
args.putInt("messageId", messageId);
frag.setArguments(args);
return frag;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
int titleId = getArguments().getInt("titleId");
int messageId = getArguments().getInt("messageId");
ResultReceiver receiver = getArguments().getParcelable("receiver");
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// dialog title
builder.setTitle(titleId);
// dialog message
builder.setMessage(messageId);
// dialog negative button
builder.setNegativeButton("No", new OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
receiver.sendResult(Activity.RESULT_CANCEL, null);
}});
// dialog positive button
builder.setPositiveButton("Yes", new OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
receiver.sendResult(Activity.RESULT_OK, null);
}});
// create the Dialog object and return it
return builder.create();
}}
然后您可以像这样处理 Receiver 中的所有内容:
Then you can handle everything in the Receiver like this:
protected void onReceiveResult(int resultCode, Bundle resultData) {
if (getActivity() != null){
// Handle result
}
}
查看 ResultReceiver 无法适应屏幕旋转了解更多详情.所以最后你可能仍然需要用你的 Activity
重新连接 ResultReceiver
.唯一的区别是您将 Activity
与 DialogFragment
解耦.
Check out ResultReceiver doesn't survire to screen rotation for more details. So in the end you probably still need to rewire the ResultReceiver
with your Activity
. The only difference is that you decouple the Activity
from the DialogFragment
.