2 bluetooth99 bluetooth99 于 2012.11.12 14:25 提问

在AlertDialog.Builder中用到findViewById()出现NullPointer异常

先看代码:

  @Override
    public void onClick(View v) {
    final AlertDialog.Builder adb = new AlertDialog.Builder(getApplicationContext());
adb.setView(LayoutInflater.from(getApplicationContext()).inflate(R.layout.custom, null));

adb.setPositiveButton("Add",new android.content.DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int arg1) {

                DatePicker datePicker = (DatePicker)findViewById(R.id.datePicker);

                java.util.Date date = null;
                Calendar cal = GregorianCalendar.getInstance();
                cal.set(datePicker.getYear(),datePicker.getMonth(), datePicker.getDayOfMonth());
                date = cal.getTime();
            }                  
        });             
adb.show();
}

在这行里出现异常:

cal.set(datePicker.getYear(),datePicker.getMonth(), datePicker.getDayOfMonth());

我尝试了用adb.findViewById();但是有错误:The method findViewById(int) is undefined for the type AlertDialog.Builder

帮忙看一下,谢谢

2个回答

clcurie_11
clcurie_11   2012.11.12 14:32
已采纳

DatePicker datePicker = (DatePicker)findViewById(R.id.datePicker);这一行改成:

DatePicker datePicker = (DatePicker)adb.findViewById(R.id.datePicker);

试下这个:

final AlertDialog.Builder adb = new AlertDialog.Builder(this);
    final View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.main1, null);
    adb.setView(view);
    final Dialog dialog;
    adb.setPositiveButton("Add",new android.content.DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int arg1) {

                    DatePicker datePicker = (DatePicker)view.findViewById(R.id.datePicker1);

                    java.util.Date date = null;
                    Calendar cal = GregorianCalendar.getInstance();
                    cal.set(datePicker.getYear(),datePicker.getMonth(), datePicker.getDayOfMonth());
                    date = cal.getTime();
                }                  
            });   
    dialog = adb.create();
    dialog.show();
bluetooth99
bluetooth99 O(∩_∩)O谢谢
大约 5 年之前 回复
lichengyuan0609
lichengyuan0609   2016.09.26 12:53

view.findViewById

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!