带标记的DialogFragment show无法正常工作

时间:2013-06-27 08:18:51

标签: android

我使用本手册http://developer.android.com/guide/topics/ui/controls/pickers.html

创建了TimePicker
public class TimePickerFragment extends DialogFragment {

    private TimePickerDialog.OnTimeSetListener mListener;
    private Activity mActivity;
    private Calendar mCalendar = Calendar.getInstance();

    public TimePickerFragment(Activity a,TimePickerDialog.OnTimeSetListener listener) {
        mListener = listener;
        mActivity = a;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current time as the default values for the picker
        int hour = mCalendar.get(Calendar.HOUR_OF_DAY);
        int minute = mCalendar.get(Calendar.MINUTE);

        // Create a new instance of TimePickerDialog and return it
        return new TimePickerDialog(mActivity, mListener, hour, minute,
                DateFormat.is24HourFormat(mActivity));
    }
}

我正试图以这种方式显示带有标记的Dialog

public class SomeActivity extends FragmentActivity implements TimePickerDialog.OnTimeSetListener {
    TimePickerFragment mTimePicker;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.some_view);

        mTimePicker = new TimePickerFragment(this, this);

        // calling show with "SOME_TAG" tag
        mTimePicker.show(this.getSupportFragmentManager(), "SOME_TAG");
    }

    @Override
    public void onTimeSet(TimePicker timePicker, int hourOfDay, int minute) {
        // Here tag is null ?!
        // Why?
        String tag = (String) timePicker.getTag();
    }
}

但是在onTimeSet方法中,tag始终为null。为什么呢?

3 个答案:

答案 0 :(得分:6)

你可以通过getTag()函数

简单地获取标签
public static class DatePickerCustom extends DialogFragment implements
            DatePickerDialog.OnDateSetListener {
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            final Calendar calendar = Calendar.getInstance();
            int yy = calendar.get(Calendar.YEAR);
            int mm = calendar.get(Calendar.MONTH);
            int dd = calendar.get(Calendar.DAY_OF_MONTH);
            return new DatePickerDialog(getActivity(), this, yy, mm, dd);
        }

        public void onDateSet(DatePicker view, int yy, int mm, int dd) {

              String mytag=getTag();

        }
    }

答案 1 :(得分:1)

我知道这是一个迟到的回复,但我最近遇到了同样的情况。所以这是我的答案,

DialogFragment.Show(FragmentManager manager, String tag)方法为Fragment本身设置了标记。所以这个标签可以按如下方式使用:

Fragment dateTo=getActivity().getSupportFragmentManager().findFragmentByTag("dateTo");
            if(dateTo!=null){
                //do something

            } 

一个用例是你可以在一个活动中显示多个片段,并识别你可以用给定标签找到该片段的片段。如果它不是空的,宾果!!!“

答案 2 :(得分:0)

在检索之前,您需要使用setTag()方法将Object设置为标记,而您在发布的代码中没有这样做。

在调用setTag()之前,getTag()将始终返回null。