我试图在Android上打开一个用于选择日期的对话框。这是我的代码:
et_date = (EditText) findViewById(R.id.et_date);
et_date.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
});
我有这堂课:
public static class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
}
}
我收到了这个错误:
尝试调用虚方法' void android.widget.EditText.setOnClickListener(android.view.View $ OnClickListener)' 在空对象引用上
我该如何解决这个问题?感谢。
答案 0 :(得分:1)
问题是:
et_date为空。您尝试为null对象设置侦听器。这就是原因,它给出了这个错误。仔细检查你的布局xml。
对于调试,只需添加空检查并将lisetner设置为" et_date"如下
if (ed_date != null)
{
// print log here to find this as error.
// set listener here..
}
从您的评论中更新:
在您的片段中添加以下代码。移动变量" ed_date"对于你的片段,它不应该在Activity中。
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ed_date = (EditText) view.findViewById(R.id.ed_date);
}