我正在制作一个使用DatePickerDialog
的Android应用。预期的功能是让用户在对话框中选择日期,然后使TextView
反映所选日期。但是,当用户选择日期时,找不到任何类型的点击侦听器来通知我的活动。我正在寻找一种方法来检测用户何时选择了日期,但是要从我的主活动中进行选择。这是我的DatePickerDialog
类:
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
private GregorianCalendar date;
@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);
}
@Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
date = new GregorianCalendar(year, month, day);
}
public GregorianCalendar getDate() {
return date;
}
}
以及启动对话框的代码:
DialogFragment datePicker = new DatePickerFragment();
datePicker.show(getSupportFragmentManager(), "datePicker");
我目前正在从扩展
Activity
的类中启动对话框,并且我正在寻找一种方法来从该类中检测用户是否从对话框中选择了日期。有什么建议么? 最佳答案
我建议阅读:Communicating with Other Fragments。Activity
必须实现DatePickerDialog.OnDateSetListener
接口:
public class MyActivity extends ActionBarActivity implements DatePickerDialog.OnDateSetListener {
...
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
// the user selected, now you can do whatever you want with it
}
}
如果将以下代码添加到
Activity
类,则在用户选择日期时将通知DialogPickerFragment
:public class DatePickerFragment extends DialogFragment {
private DatePickerDialog.OnDateSetListener mListener;
@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(), mListener, year, month, day);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (!(context instanceof DatePickerDialog.OnDateSetListener)) {
throw new IllegalStateException("Activity must implement fragment's callbacks.");
}
mListener = (DatePickerDialog.OnDateSetListener) activity;
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
}
关于android - DatePickerDialog监听器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29273514/