程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> android-在AlertDialog.Builder中用到findViewById()出現NullPointer異常

android-在AlertDialog.Builder中用到findViewById()出現NullPointer異常

編輯:編程綜合問答
在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

幫忙看一下,謝謝

最佳回答:


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();
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved