我正在使用谷歌示例使用对话框片段
http://developer.android.com/guide/topics/ui/controls/pickers.html在我的应用程序中插入一个日期选择器
但我不确定如何在设置日期后获取日期(不是 java 专家)。对话框和日期选择器运行正常,我可以记录正确设置的日期,但是,我怎样才能在父活动上执行回调?
这是我的对话框片段
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);
}