在我的应用程序中,我有一个45“editText”。现在,当用户旋转设备时,对话框关闭,所有数据都消失了。所以我在Dialogclass中创建了一个“public static boolean isShow = false”变量,它的对话框是“show”,而我的MainActivity上我保存到了bundle中它的工作我的对话框没有关闭,因为我创建了一个新的对话框,当时“ isShow“= false。但所有数据都已清除。我的问题是我需要逐个保存所有45个editText吗?如果我需要,有一种方法可以取消此对话框的旋转?
public class DialogSetting extends Dialog {
public static boolean isShow = false;
public DialogSetting(Context context) {
super(context);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.dialog_setting);
this.context = context;
this.show();
isShow = true;
this.setOnCancelListener(new DialogInterface.OnCancelListener()
{
@Override
public void onCancel(DialogInterface dialog)
{
isShow = false;
}
});
}
public void close(View v){
isShow = false;
this.dismiss();
}
MainActivity:
@Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
outState.putBoolean("dialogSetting", DialogSetting.isShow);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onRestoreInstanceState(savedInstanceState);
DialogSetting.isShow = savedInstanceState.getBoolean("dialogSetting");
if(DialogSetting.isShow){
new DialogSetting(this);
}
答案 0 :(得分:0)
首先:您应该从DialogFragment
继承对话框。如果您这样做,FragmentManager
将在旋转设备后重新创建片段。
所以这里是你的Dialog类应该是这样的:
public class MyDialog extends DialogFragment {
public static MyDialog newInstance(){
MyDialog f = new MyDialog();
return f;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_setting, container, false);
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
// Everything else that needs to be done to setup the dialog (findViewById, Listener etc.)
return view;
}
}
以下是调用Dialog的方法(稍微复杂一些):
FragmentTransaction ft = getFragmentManager().beginTransaction();
Fragment prev = getFragmentManager().findFragmentByTag("dialog");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
MyDialog dialogFragment = MyDialog.newInstance();
dialogFragment.show(ft, "dialog");
为防止因旋转而导致数据丢失,您需要将数据保存在对话框内的数据包中(基本上与您在Activity
中的操作相同)。
以下是保存EditText
的输入文本的基本示例:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState != null){
text = savedInstanceState.getString("et_text");
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("et_text", mEditText.getText().toString());
}
您可以在docs(click)中详细了解DialogFragments
。