我只是想从我在网上找到的许多android datepicker教程中创建的一个datepicker对话框中获取日期。一旦选中,我在实际检索文本日期的某个地方似乎出错了。我有一个DatePickerFragment类,它从一个CreateEvent片段调用,该片段嵌套在我的MainActivity活动类中。这是DatePicker:
public class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
private EditText txtDate;
@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) {
txtDate = (EditText)view.findViewById(R.id.txtDate);
txtDate.setText(day + " " + (month + 1) + " " + year);
}
}
当我实际尝试设置日期时,我得到Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence) on a null object reference
,我理解这意味着它实际上无法在我的创建事件片段xml文件中找到edittext元素。
我应该如何设置{edit}元素的文本来自onDateSet
,还是我必须改变我的方法?
我试了this way,但无济于事。
答案 0 :(得分:1)
我是通过以下代码行完成的:
public class DatePickerDialogMy extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
DateSetting dateSetting=new DateSetting(getActivity());
Calendar calendar= Calendar.getInstance();
int year= calendar.get(calendar.YEAR);
int month=calendar.get(calendar.MONTH);
int day=calendar.get(calendar.DAY_OF_MONTH);
DatePickerDialog dialog;
dialog=new DatePickerDialog(getActivity(),dateSetting,year,month,day);
return dialog;
}
}
第二课:
public class DateSetting implements android.app.DatePickerDialog.OnDateSetListener {
Context context;
public DateSetting(Context context){
this.context=context;
}
@Override
public void onDateSet(DatePicker view, int year, int dateSetting, int dayOfMonth) {
Toast.makeText(context, "selected date:" + dateSetting + "/" + dayOfMonth + "/" + year, Toast.LENGTH_LONG).show();
// MainActivity.test.setText(String.valueOf(dateSetting));
MyActivity.dobEditText.setText(dateSetting+"/"+dayOfMonth+ "/" + year);
}
}
如何致电:
DatePickerDialogMy datePickerDialog = new DatePickerDialogMy();
datePickerDialog.show(getSupportFragmentManager(), "date_picker");
答案 1 :(得分:1)
您需要使用界面来获取datepicker
到来电者fragment
的数据:
public interface DateListener {
void passDate(String date);
}
创建名为mListener
的成员变量:
private DateListener mListener;
覆盖onAttach
& onDetach
fragment
方法:
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (DateListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement DateListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
接下来,在来电者interface
中实施此fragment
并覆盖passDate
方法:
@Override
public void passDate(String date) {
// Do something with 'date', yourEditText.setText(date) for the example
}
你应该好好去。