自定义警报对话框无法关闭

时间:2018-09-18 12:29:45

标签: android alertdialog android-alertdialog application-settings

我想实施对R.id.textSizeA按钮的关闭,但是不起作用。有人可以帮忙吗?自定义警报对话框具有许多用于其设置的单选按钮。当我按下单选按钮时,它应该关闭对话框,但是我不知道该怎么办。

 final LinearLayout textSizeBtn = (LinearLayout) findViewById(R.id.text_size_btn);
    textSizeBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(final View view) {

            final AlertDialog.Builder alertDialog = new AlertDialog.Builder(view.getContext());

            final LayoutInflater layoutInflater = LayoutInflater.from(view.getContext());
            final View view1 = layoutInflater.inflate(R.layout.font_size_dialog, null);
            alertDialog.setView(view1);


            RadioGroup radioGroup = (RadioGroup) view1.findViewById(R.id.textSizeChanGroup);
            radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {

                    TextView sampleText = (TextView) view1.findViewById(R.id.texSize_sampleText);

                    if (checkedId == R.id.textSizeA) {
                        String size = String.valueOf(12);
                        sampleText.setTextSize(Float.parseFloat(size));
                        textSizeHint.setText(size);
                        SharedPreferences.Editor editor = view.getContext().getSharedPreferences(String.valueOf(R.string.textSizePref), MODE_PRIVATE).edit();
                        editor.putString("textSizeA", size);
                        editor.clear();
                        editor.apply();

                    } else if (checkedId == R.id.textSizeB) {
                        String size = String.valueOf(13);
                        sampleText.setTextSize(Float.parseFloat(size));
                        textSizeHint.setText(size);
                        SharedPreferences.Editor editor = view.getContext().getSharedPreferences(String.valueOf(R.string.textSizePref), MODE_PRIVATE).edit();
                        editor.putString("textSizeA", size);
                        editor.clear();
                        editor.apply();

                    }
                }
            });
            alertDialog.create().show();

        }
          });

2 个答案:

答案 0 :(得分:1)

尝试一下

更改

alertDialog.create().show();

AlertDialog alert = alertDialog.create();
alert.show();

现在使用alert解除警报,如下所示

if (checkedId == R.id.textSizeA) {
    String size = String.valueOf(12);
    ...
    ...
    editor.apply();
    alert.dismiss(); // add this
} else if
...
...

答案 1 :(得分:0)

替换此行

final AlertDialog.Builder alertDialog = new AlertDialog.Builder(view.getContext());

final AlertDialog alertDialog = new AlertDialog.Builder(view.getContext());

还有这个

alertDialog.create().show();

alertDialog.show(); 并在需要关闭警报对话框时致电alertDialog.dismiss();