我正在使用谷歌的示例,尝试在我的应用程序中使用DialogFragment插入一个日期选择器。
http://developer.android.com/guide/topics/ui/controls/pickers.html
但是我不确定如何在设置日期后获取它(不是java专家)。对话框和日期选择器都可以正常运行,并且我可以记录日期已正确设置,但是,我该如何在父活动上执行回调?
这是我的Dialog fragment:
public 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) {
**Log.w("DatePicker","Date = " + year);**
}
}
...我从我的活动中调用对话框...
public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
在我的父活动中调用一个方法的正确方法是什么,而不是使用 Log.w?我想这可能涉及将回调作为参数传递或类似的内容,但我在互联网上找到的大多数参考资料都是关于没有对话框片段的早期版本。
编辑:不确定是否重要,但父活动被声明为:
public class EditSessionActivity extends FragmentActivity {
解决方案:感谢Lecho用户,以下是正确的方法
DatePickerFragment.class
public class DatePickerFragment extends DialogFragment{
@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(), (EditSessionActivity)getActivity(), year, month, day);
}
}
...并且父活动为EditSessionActivity.class...
public class EditSessionActivity extends FragmentActivity implements OnDateSetListener {
...
@Override
public void onDateSet(DatePicker view, int year, int month, int day) {
//do some stuff for example write on log and update TextField on activity
Log.w("DatePicker","Date = " + year);
((EditText) findViewById(R.id.tf_date)).setText("Date = " + year);
}