Android AlertDialog无法通过单选按钮关闭

时间:2019-02-07 20:51:33

标签: android radio-button alertdialog

我有一个带单选按钮的AlertDialog。当我单击一个选项时,它将值插入到文本视图中,但之后无法关闭窗口。

private void showRadioButtonDialog() {
    LayoutInflater inflater =(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View vewInflater = inflater.inflate(R.layout.dialog_installments_radiogroup,  null);
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    final AlertDialog dialog = builder.create();
    builder.setView(vewInflater);
    builder.setTitle("Dialog title");
    RadioGroup currencySettingRadioGroup = vewInflater.findViewById(R.id.radio_group);
    ArrayList<String> listArr = getInstallmentsList(amountToPay, 12);
    for ( String items: listArr ) {
        RadioButton rb = new RadioButton(this);
        rb.setText(items);
        currencySettingRadioGroup.addView(rb);
        rb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rb.setChecked(true);
                TextView tvInstallments = findViewById(R.id.tvInstallments);
                tvInstallments.setText(items);
                dialog.dismiss(); // <== does not work
            }
        });

    }
    builder.show();
}

1 个答案:

答案 0 :(得分:1)

show()方法在内部调用create()

您可以通过调用builder.create()获得对内置对话框的引用,但是当您调用builder.show()时Android也会这样做。这意味着Android拥有自己的Dialog实例,您的dialog变量未引用该实例。

使用dialog.show()代替builder.show()

设置完Builder的所有属性后,还需要调用builder.create()(将其移动到builder.setTitle()之下)。