首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用dialogfragment从datepicker获取日期

使用dialogfragment从datepicker获取日期
EN

Stack Overflow用户
提问于 2012-07-18 00:41:28
回答 9查看 75.7K关注 0票数 54

我正在使用google示例使用对话片段在我的应用程序中插入一个datepicker

http://developer.android.com/guide/topics/ui/controls/pickers.html

但是我不确定在设置之后如何获取日期(不是java专家)。对话框和日期选择器运行正常,我可以记录日期已正确设置,但是,我如何才能在父活动上执行回调?

这是我的对话框片段

代码语言:javascript
运行
复制
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我从我的活动中调用对话框...

代码语言:javascript
运行
复制
public void showDatePickerDialog(View v) {
    DialogFragment newFragment = new DatePickerFragment();
    newFragment.show(getSupportFragmentManager(), "datePicker");
}

在父activity中调用方法而不是Log.w的正确方式是什么?我认为这与将回调作为参数传递有关,但我在互联网上找到的大多数参考资料都是关于没有对话片段的早期版本的。

编辑:不确定它是否重要,但父活动声明为:

代码语言:javascript
运行
复制
public class EditSessionActivity extends FragmentActivity {

解决方案:感谢Lecho user,这就是实现它的方法

DatePickerFragmennt.class

代码语言:javascript
运行
复制
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...

代码语言:javascript
运行
复制
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);
    }
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11527051

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档