Search code examples
androidandroid-alertdialogapplication-settings

Custom alert dialog not dismiss


I want to implement dismiss to R.id.textSizeA button, but it's not working. Anyone can help? The custom alert dialog has lots of radio buttons for its settings. When I press the radio button it should close the dialog, but I don't know how to do.

 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();

        }
          });

Solution

  • Try this

    Change

    alertDialog.create().show();
    

    to

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

    now use alert to dismiss the alert like below

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