Метод alertDialog.getButton() дает исключение нулевого указателя android

Я планирую создать 3 кнопки с layout_weight = 1, меня не интересует пользовательский диалог. Поэтому я написал код ниже. Он не работает. Кнопка «Всегда да» дает мне ноль. Что не так в этом коде?

  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-разработчик.


person ADIT    schedule 05.01.2011    source источник


Ответы (3)


Посмотрите здесь ответ: http://code.google.com/p/android/issues/detail?id=6360

Как сказано в комментарии № 4, вы должны вызвать show() в своем диалоговом окне, прежде чем сможете получить доступ к кнопкам, они недоступны заранее. Для автоматического решения о том, как изменить кнопки, как только они будут готовы, см. ответ Микки

person vieux    schedule 05.01.2011
comment
Проблема сохраняется. Не используйте эту ссылку. - person ADIT; 05.01.2011
comment
Пожалуйста, прочтите комментарий №4, используйте dialog.show(); перед использованием getButton() - person vieux; 05.01.2011

Это работает для меня:

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

person Mickey Tin    schedule 30.01.2013
comment
setOnShowListener — это API 8+. - person Ε Г И І И О; 24.06.2014

Спасибо. Но для понимания целей новых разработчиков я переписываю код ниже.

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);        
person ADIT    schedule 05.01.2011