6

我使用本手册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));
    }
}

我正在尝试以这种方式显示带有标签的此对话框

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。为什么?

4

3 回答 3

7

您可以通过 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();

        }
    }
于 2013-11-08T05:17:25.697 回答
2

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

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

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

            } 

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

于 2014-04-07T12:52:58.610 回答
0

在检索对象之前,您需要使用该setTag()方法将其设置为标记,而您在发布的代码中的任何地方都没有这样做。

直到setTag()被调用,getTag()将始终返回 null。

于 2013-06-27T08:20:06.060 回答