How to add a check box to an alert dialog

后端 未结 4 1107
臣服心动
臣服心动 2020-12-13 12:10

Currently when the user opens my app, an AlertDialog opens, asking them if they would like to upgrade to the pro version.

I need to add a CheckBox

4条回答
  •  一整个雨季
    2020-12-13 12:55

    You could use a multichoicelist with only one item:

    final boolean[] checked = new boolean[] {false};
    builder.setMultiChoiceItems(new String[]{"Remember decision"}, checked, new DialogInterface.OnMultiChoiceClickListener() {
                   @Override
                   public void onClick(DialogInterface dialogInterface, int i, boolean b) {
                       checked[i] = b;
                   }
               });
    

    Then in the OnClick() of an alert dialog button you can check the value of checked[0]and save that value in your app's Sharedpreferences:

    builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                       @Override
                       public void onClick(DialogInterface dialogInterface, int i) {
                           if(checked[0]){
                               SharedPreferences.Editor editor = settings.edit();
                               editor.putBoolean("preferences_never_buy_pro", true);
                               editor.apply();
                           }
                           dialog.cancel();
    
                       }
                   });
    

    With this preference you can decide whether the dialog should be shown again in the future.

提交回复
热议问题