我正在制作一个使用 DatePickerDialog
的 Android 应用程序。预期的功能是让用户在对话框中选择一个日期,然后让 TextView
反射(reflect)所选日期。但是,当用户选择日期时,我找不到任何类型的点击监听器来通知我的 Activity。我正在寻找一种方法来检测用户何时选择了日期,但来 self 的主要 Activity 。这是我的 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
接口(interface):
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
}
}
如果您将以下代码添加到 DialogPickerFragment
类,Activity
将在用户选择日期时收到通知:
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/