简体   繁体   English

销毁并重新创建活动后处理重新创建的对话框片段的最佳方法

[英]Best way of handling recreated dialog fragment after activity is destroyed and recreated

I have an activity which may show some DialogFragments. 我有一个活动,可能显示一些DialogFragments。 This activity needs to get the response from the dialogs. 此活动需要从对话框获取响应。 I use a listener. 我使用一个监听器。 In activity: 活动中:

ProgressMarkDialog dialog = new ProgressMarkDialog();
dialog.setOnProgressMarkSelected(new ProgressMarkDialog.OnProgressMarkSelected() {
    @Override
    public void onSelect(final int a) {
    //some code..
        }
});

In the dialog: 在对话框中:

public void setOnProgressMarkSelected(OnProgressMarkSelected onProgressMarkSelected) {
    this.onProgressMarkSelected = onProgressMarkSelected;
}

This code works fine until somehow the activity is destroyed, but the dialog still open. 该代码可以正常工作,直到以某种方式破坏了活动,但对话框仍然打开。 The program will crash with NullPointerException because the onProgressMarkSelected is null. 由于onProgressMarkSelected为null,该程序将崩溃并显示NullPointerException。

I can use 我可以用

@Override
public void onAttach(final Activity activity) {
    super.onAttach(activity);
    onProgressMarkSelected = (OnProgressMarkSelected) activity;
}

and implement the interface in the activity. 并在活动中实现接口。 But if I have few DialogFragments, that means I should implement few interface in the activity and the code will be very messy. 但是,如果我没有几个DialogFragments,那意味着我应该在活动中实现几个接口,并且代码将非常混乱。 What is the Android best practice for this case? 在这种情况下,Android最佳做法是什么?

In my opinion the best way is to stick to the standard positive/negative buttons and attaching DialogInterface.OnClickListener as shown in the http://developer.android.com/reference/android/app/DialogFragment.html 我认为最好的方法是坚持使用标准的正/负按钮,并附加DialogInterface.OnClickListener ,如http://developer.android.com/reference/android/app/DialogFragment.html中所示

Look at it this way: standard Android user expects to see positive and/or negative button in the dialog. 这样看:标准的Android用户希望在对话框中看到肯定和/或否定按钮。 The Activity -if needed- should only be informed about the result (positive, negative input data) of the dialog. 仅应将对话框的结果(正,负输入数据)通知活动(如果需要)。 Any other input validation should be handled inside the DialogFragment 任何其他输入验证应在DialogFragment内部处理

You could use inheritance with interfaces. 您可以对接口使用继承。 Because on interfaces multiple inheritance is possible like this: 因为在接口上可以这样进行多重继承:

public interface A(){
    void doA();
}

public interface B(){
    void doB();
}

public interface BundleAB extends A, B {
    void justAnotherMethod();
}

With this you can bundle your interfaces and use it like this: 有了它,您可以捆绑您的接口并像这样使用它:

public class MyClass implements BundleAB {
    @Override
    public void doA(){}

    @Override
    public void doB(){}

    @Override
    public void justAnotherMethod(){}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM