我試圖在一個單獨的類中設置我的日期選擇器,基本上保持我的代碼清潔。我的代碼在活動上使用時有效,但是當我嘗試在View.OnclickListener上使用它時,我似乎無法獲取正確的上下文,並且收到context.getsystemservice錯誤。你能發現我做錯了什麼嗎?ViewPicker的日期選擇器.Onclicklistener
View.onclicklistener
public class SelectDate extends Activity implements View.OnClickListener {
public Context context;
public EditText selectDate;
public SelectDate(EditText selectDate) {
this.selectDate = selectDate;
}
int year_x, month_x, day_x;
int dateInt;
DatePickerDialog dialog;
@Override
public void onClick(View v) {
InputMethodManager im = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(selectDate.getWindowToken(), 0);
dialog = new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
year_x = year;
month_x = monthOfYear;
day_x = dayOfMonth;
int month = monthOfYear + 1;
String date = dayOfMonth + "";
if (date.length() == 1)
date = "0" + date;
date = month + date;
selectDate.setText(dayOfMonth + "/" + month + "/" + year);
dateInt = Integer.parseInt(date);
}
}
,year_x,month_x,day_x);
// Disable dates in the past
dialog.getDatePicker().
setMinDate(System.currentTimeMillis()-1000);
dialog.show();
}
}
設置的onclick聽衆
EditText selectDate = (EditText)convertView.findViewById(R.id.editDate);
convertView.findViewById(R.id.editDate).setOnClickListener(new SelectDate(selectDate));
錯誤消息
android.content.Context.getSystemService(java.lang.String)' on a null object reference
嘗試從視圖獲取上下文v –