将变量从片段传递给活动(datepicker)

时间:2015-01-26 18:25:17

标签: android android-fragments datepicker

我是android编程的新手,我有时会遇到一些问题。我必须将DatePicker Dialog片段选择的日,月和年传递给调用片段的Activity。我用过使用android指南代码:

public static 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) {
        // Do something with the date chosen by the user
    }
}

我已经在另一个论坛上问过,他们建议我覆盖show()方法来传递另一个这样的变量:

@Override
public void show (FragmentManager manager, String tag, DatePickerDialog.OnDateSetListener dateSetListener) {
  super(manager, tag);
  this.dateSetListener = dateSetListener;
}

没办法,它不起作用。我该怎么办?

抱歉我的英语不好和愚蠢的问题:( 提前致谢, 达米亚诺

编辑:

我已经通过实现接口查看了代码,但我仍然遇到问题:

public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
    onDataSceltaListener 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(), this, year, month, day);
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        mListener.onDataScelta(year,month,day);

    }

    public interface OnDataSceltaListener {
        public void onDataScelta(int year, int month, int day);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnDataSceltaListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener");
        }
    }
}

有什么问题? :(

0 个答案:

没有答案