具有首选项的警报对话框

时间:2014-01-06 18:57:39

标签: android

我正在做一个改变背景颜色的应用程序,但我现在想要做的就是使用alertDialog和我的问题是当我更改屏幕时它没有保存最后一次更改,它再次出现alertDialog。我正在使用这个,但我不知道我是否正确...我正在使用getPreferences,因为我需要让我的活动默认使用SharedPreferences

//        SharedPreferences preferences = getPreferences(MODE_PRIVATE);
//        int storedPreference = preferences.getInt("storedInt", 0);
//        SharedPreferences.Editor editor = preferences.edit();
//        editor.putInt("storedInt", storedPreference);
//        editor.commit();

        new AlertDialog.Builder(this)
        .setTitle("Alert Dialog")
        .setMessage("Startup Button Visibility:")
        .setPositiveButton("Hidden", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) { 
                if(buttonVisible == true)
                {
                    myLayout2.setVisibility(View.INVISIBLE);
                }
                else
                    myLayout2.setVisibility(View.VISIBLE);
//              Toast.makeText(getApplicationContext(), "Hidden was clicked", Toast.LENGTH_LONG).show();
//                // continue with delete
            }
         })

        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) { 
                // do nothing
            }
         })

         .setNeutralButton("Visible", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub  
            }
         })

         /**
          * Showing alert dialog
          */

        .show();

3 个答案:

答案 0 :(得分:0)

根据您对问题的评论。即使您更改了方向,看起来您仍希望保留活动状态。将其添加到活动括号内的清单中。

android:configChanges="orientation|screenSize"

更改方向会重新创建活动。

答案 1 :(得分:0)

当您更改方向时,问题是这样每次都会调用onCreate()但您可以通过在活动标记的AndroidManifest文件中添加Activity的configChanges属性来避免重新创建Activity。

机器人:configChanges = “keyboardHidden |取向”

答案 2 :(得分:0)

当您在发生事件后更改屏幕的方向时。

===方向改变===

onSaveInstanceState - > onPause - > onStop - > onCreate - > onStart - > onRestoreInstanceState - >的onResume。

因此,当您想要保存状态时,可以使用onSaveInstanceState()。通常你会在onCreate()恢复你的状态。

protected void onSaveInstanceState(Bundle icicle) {
  super.onSaveInstanceState(icicle);
  icicle.putString("param", value);
}

并恢复:

public void onCreate(Bundle icicle) {
  if (icicle != null){
    value = icicle.getString("param");
  }
}

因此您可以保存颜色值或您想要的任何内容,并在onCreate()中将其恢复并设置为AlertDialog