2011-05-12 92 views
2

如何在android中保存对话框的状态?我有下面的单选按钮对话框,但不知道如何保存对话框的状态。感谢您的帮助对话框的Android保存状态

final CharSequence[] items = {"Item 1", "Item 2", "Item 3"}; 
AlertDialog.Builder builder = new AlertDialog.Builder(Tweaks.this); 
builder.setTitle("Pick an item"); 
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() { 
    public void onClick(DialogInterface dialog, int item) { 
     Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show(); 
    } 
}).show(); 

回答

1

您应该在用户点击时存储所选项目的位置。然后,当您显示列表时,查找先前存储的索引。如果没有以前存储的值,则返回-1。

我有一个应用程序首选项辅助类...

public class AppPreferences { 
    private static final String APP_SHARED_PREFS = "myApp_preferences"; // Name of the file -.xml 
    private SharedPreferences appSharedPrefs; 
    private Editor prefsEditor; 

    public AppPreferences(Context context) 
    { 
     this.appSharedPrefs = context.getSharedPreferences(APP_SHARED_PREFS, Activity.MODE_PRIVATE); 
     this.prefsEditor = appSharedPrefs.edit(); 
    } 

    public int getItemIndex() { 
     return appSharedPrefs.getInt("itemIndex", -1); 
    } 

    public void saveItemIndex(int i) { 
     prefsEditor.putInt("itemIndex", i); 
     prefsEditor.commit(); 
    } 
} 

然后,在我的代码创建一个字段变量...

protected AppPreferences appPrefs; 

和实例化活动中的一个实例的onCreate()...

appPrefs = new AppPreferences(getApplicationContext()); 

然后替换为您的 “-1” ...

builder.setSingleChoiceItems(items, appPrefs.getItemIndex(), new DialogInterface.OnClickListener() { 

而在你的onClick(),请确保您...

appPrefs.saveItemIndex(item); 
0

我在DialogFragment成员变量保存的状态。以下代码保存对话框关闭时的状态,但当应用程序关闭时,不是

public class MyDialogFragment extends DialogFragment { 

    //this is the default value, set when the dialog is created 
    private String myValue = "any initial String"; 
    private TextEdit myTextEdit; 

    @Override 
    public Dialog onCreateDialog(Bundle savedInstanceState) { 

     //construct the dialog 
     AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 
     LayoutInflater inflater = getActivity().getLayoutInflater(); 
     ViewGroup myView = (ViewGroup)inflater.inflate(R.layout.my_view, null); 
     builder.setView(myView); 

     //find the view and set the value 
     myTextEdit = (TextView)myView.findViewById(R.id.my_text_edit); 
     myTextEdit.setText(myValue); 

     return builder.create(); 
    } 

    @Override 
    public void onDismiss(DialogInterface dialog) { 
     super.onDismiss(dialog); 

     //when the dialog is dismissed, save the users input and overwrite the initial value 
     myValue = myTextEdit.getText(); 

    } 
}