Java – I can’t create a default constructor from a class that extends dialogfragment, and I’ve created my own custom constructor

I'm confused about the error message about the default constructor

I have two classes mainactivity and resultdialog Some methods in mainactivity create a new dialog box and pass 2strings to the custom constructor in resultdialog

Resultdialog extends dialogfragment So I defined my own constructor, but when there was an error, I just created a parameterless constructor, but it is still not allowed to do so

I have searched for abit on so, but the answer is a little explanatory. Screen rotation may break and recreate the screen using the default constructor, but I still can't answer how to solve this problem

Someone please help me, I'm a little confused Part of my resultdialog class:

public class ResultDialog extends DialogFragment {

private String message;//to hold the message to be displayed
private String title;//for alert dialog title

//constructor for the dialog passing along message to be displayed in the alert dialog
public ResultDialog(String message,String title){
    this.message = message;
    this.title = title;

}

public ResultDialog(){
    //default constructor
}

Solution

You can use newinstance Check document

http://developer.android.com/reference/android/app/Fragment.html

And check it

Why do I want to avoid non-default constructors in fragments?

ResultDialog rd = ResultDialog.newInstance("message","title");

then

public static ResultDialog newInstance(String message,String title) {
    ResultDialog f = new ResultDialog();
    Bundle args = new Bundle();
    args.putString("message",message);
    args.putString("title",title);
    f.setArguments(args);
    return f;
}

And use getarguments () to retrieve the value

String message = getArguments().getString("message");
String title = getArguments().getString("title");

getArguments()

public final Bundle getArguments ()

Added in API level 11
Return the arguments supplied when the fragment was instantiated,if any.
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>