通过对话框更改首选项

时间:2013-09-03 16:50:13

标签: android dialog sharedpreferences android-preferences

如果用户在输出对话框中选择“确定”,我想更改班级中的首选项。为此我在课堂上实现了这个方法:

if (basalcor != basal) {

                    FragmentManager fragmentManager = getFragmentManager();
                    ChangeBasalDialog dialogo = new ChangeBasalDialog(basal);
                    dialogo.show(fragmentManager, "tagbasal");
                    if (dialogo.check == true) {
                        String ok= "Basal factor changed succesfully";
                        SharedPreferences.Editor prefsEditor = myprefs.edit();
                        if (basalMorFrame == true) {
                            prefsEditor.putString("basalMor", String.valueOf(basal));
                            prefsEditor.commit();
                            Toast toast=Toast.makeText(Mymeasures.this, ok, Toast.LENGTH_SHORT);
                            toast.show();
                        }   
                        if (basalNiFrame == true) {
                            prefsEditor.putString("basalNi",
                                    String.valueOf(basal));
                            prefsEditor.commit();
                            Toast toast=Toast.makeText(Mymeasures.this, ok, Toast.LENGTH_SHORT);
                            toast.show();
                        }
                    }
                    }

这是类ChangeBasalDialog:

    public class ChangeBasalDialog extends DialogFragment{
     double basal=0;
     boolean check=false;
     @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {

            AlertDialog.Builder builder =
                    new AlertDialog.Builder(getActivity());

            builder.setMessage("The system recommends you now a new Basal factor ("+String.valueOf(basal)+"). Do you want to set the new one as default?")
            .setTitle("New Basal recommendation avaliable")
            .setPositiveButton("Yes, i want", new DialogInterface.OnClickListener()  {
                   public void onClick(DialogInterface dialog, int id) {
                            check=true;
                            dialog.cancel();
                       }
                   })
            .setNegativeButton("No, I'll keep my old value", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                       }
                   });

            return builder.create();
        }



     public ChangeBasalDialog (double a){
     basal=a;
     }
}

问题是,即使按下OK,dialogo.check也始终为false,然后我无法改变我的偏好。我只是想让它返回dialogo.check = true,当我按下OK按钮但我已经尝试了所有内容而我根本看不到它。提前致谢

1 个答案:

答案 0 :(得分:1)

执行此操作时:dialog.cancel();您重置所有变量。

我建议你在ChangeBasalDialog之外使用布尔检查(如果你在另一个活动中有这个ChangeBasalDialog)。

或者为DialogFragment实现一个侦听器,this是一个记录良好的示例。