在AlertDialog.Builder中更改NegativeButton的文本

时间:2013-12-16 12:21:04

标签: android android-alertdialog

我已经创建了AlertDialog.Builder子类来创建我自己的自定义对话框。在该对话框中,我添加了CheckBox。我想要的是在检查NegativeButton时将Cancel的文字从CheckBox更改为其他内容:

myCheckbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {           
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            // change text of negative button
        }
    }
});

我该怎么做?

我尝试使用

获取对该按钮的引用
Button btnNegative = (Button)dlgView.findViewById(android.R.id.button1);

但返回null

2 个答案:

答案 0 :(得分:1)

<强>更新

Calling findViewById() will search for views within your Activity's layout and not your dialog's view. You need to call findViewById() on the specific View that you set as your dialog's layout.

View dialogView = inflater.inflate(R.layout.search_dialog, null);
searchDialog.setView(dialogView);
EditText tagText = (EdiText) dialogView.findViewById(R.id.tagField); 
searchDialog.setPositiveButton( ... ) ...
AlertDialog myAlert = searchDialog.create(); //returns an AlertDialog from a Builder.
myAlert.show();

尝试这可能是有用的从博客阅读,可能是有用的

AlertDialog dialog = your_builder.create();

Button b = dialog.getButton(DialogInterface.BUTTON_NEGATIVE);

答案 1 :(得分:0)

我能够获得创建的AlertDialog的实例,并使用它的按钮:

class MyBuilder extends AlertDialog.Builder {
    AlertDialog myDialog;

    @Override
    public AlertDialog show() {
        myDialog = super.show();

        return myDialog;
    }

    public MyBuilder(Activity act) {
        CheckBox cb = ... ;
        cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {           
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Button btnNegative = myDialog.getButton(AlertDialog.BUTTON_NEGATIVE);
            }
        });
    }
}