我正在使用google示例使用对话片段在我的应用程序中插入一个datepicker
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);**
}
}
...and我从我的活动中调用对话框...
public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
在父activity中调用方法而不是Log.w的正确方式是什么?我认为这与将回调作为参数传递有关,但我在互联网上找到的大多数参考资料都是关于没有对话片段的早期版本的。
编辑:不确定它是否重要,但父活动声明为:
public class EditSessionActivity extends FragmentActivity {
解决方案:感谢Lecho user,这就是实现它的方法
DatePickerFragmennt.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);
}
}
...and父活动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);
}
https://stackoverflow.com/questions/11527051
复制相似问题