Метод alertDialog.getButton() указывает на исключение
Я планирую создать 3 кнопки с layout_weight = 1, не интересующихся пользовательским диалогом. Так что я написал код ниже. Это не работает. Всегда да, кнопка дает мне null.
Что не так в этом коде?
AlertDialog dialog= new AlertDialog.Builder(this).create();
dialog.setIcon(R.drawable.alert_icon);
dialog.setTitle("title");
dialog.setMessage("Message");
dialog.setButton(AlertDialog.BUTTON_POSITIVE,"Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
Button yesButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
Log.w("Button",""+yesButton);//here getting null
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1f);
yesButton.setLayoutParams(layoutParams);
dialog.show();
С уважением,
Разработчик Android.
Ответы
Ответ 1
Взгляните сюда на ответ: http://code.google.com/p/android/issues/detail?id=6360
Как говорится в комментарии # 4, вы должны вызвать show()
в своем диалоговом окне, прежде чем вы сможете получить доступ к кнопкам, они недоступны заранее. Для автоматического решения о том, как изменить кнопки, как только они будут готовы, см. ответ Микки
Ответ 2
Это работает для меня:
AlertDialog alertDialog = new AlertDialog.Builder(this)
.setMessage(message)
.setCancelable(true)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do smthng
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do snthn
}
}).create();
alertDialog.setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialog) { //
Button positiveButton = ((AlertDialog) dialog)
.getButton(AlertDialog.BUTTON_POSITIVE);
positiveButton.setBackgroundDrawable(getResources()
.getDrawable(R.drawable.btn_default_holo_dark));
Button negativeButton = ((AlertDialog) dialog)
.getButton(AlertDialog.BUTTON_NEGATIVE);
positiveButton.setBackgroundDrawable(getResources()
.getDrawable(R.drawable.btn_default_holo_dark));
}
});
alertDialog.show();
только в этом порядке, вызовите alertDialog.setOnShowListener
после create()
Ответ 3
Спасибо wieux.But для новых разработчиков, понимающих цель Iam переписывая код ниже
AlertDialog dialog= new AlertDialog.Builder(this).create();
dialog.setIcon(R.drawable.alert_icon);
dialog.setTitle("title");
dialog.setMessage("Message");
dialog.setButton(AlertDialog.BUTTON_POSITIVE,"Yes", new DialogInterface.OnClickListener() { @Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
dialog.show();
Button yesButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE); Log.w("Button",""+yesButton);//here getting null LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1f); yesButton.setLayoutParams(layoutParams);