3

I have created an DialogFragment which is building and returning AlertDialog from onCreateDialog method. The AlertDialog contains two EditText views.

I'm setting the initial values of these two edit texts in the onCreateDialog method which works great until I rotate the phone and all changes get lost/restored to initial values because the onCreateDialog is recalled.

So my question is where should I place the initial values so they are only set the very first time you open the dialog and if you have done changes and you rotate your phone, the last state i retained and retached?

Below I have pasted simplified version of my code. One solution could be initializing the class attributes at newInstance() method, but then I need to make them static. Other solution could be passing the values through the Bundle, but no put-methods take Calendar as parameter type.

What is best practice?

public class MyDialogFragment extends DialogFragment implements OnClickListener, OnDateSetListener, OnQuantitySetListener 
{
private EditText editText1, editText2
private MyObject myObject;


public static MyDialogFragment newInstance() 
{
    return new MyDialogFragment ();
}


@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    LayoutInflater factory = LayoutInflater.from(getActivity());
    final View v = factory.inflate(R.layout.my_layout, null);

    editText1 = (EditText) v.findViewById(R.id.text1);
    editText2 = (EditText) v.findViewById(R.id.text2);

    myObject = <get the object from database>;

    editText1.setText(myObject.attribute1);
    editText2.setText(myObject.attribute2);


    bindDataToViews();

    return new AlertDialog.Builder(getActivity())
            .setIconAttribute(R.drawable.add)
            .setTitle("Title of the dialog")
            .setView(v)).create();
}

... other methods using getting the values from EditText and putting them back to MyObject

}

4

2 回答 2

2

Calendar is Serializable so you can put it as that in the Bundle.

于 2012-08-13T20:46:43.290 回答
-1

You can store your data in onSaveInstanceState(Bundle outState) method, and read them again in onRestoreInstanceState() method. onSaveInstanceState will be called before screen rotation, and onRestoreInstanceState() after change. This is a good place to store data between orientation changes.

Or you can also add in Manifest file

android:configChanges="orientation"

Add this value to activitiy, which contains your alertDialog.

于 2012-08-13T20:46:12.573 回答