1

我有一个工作的 TimePickerFragment,它使用当前时间作为选择器的默认值。现在我想传递旧的分钟和小时选择值以显示在选择器中。我怎样才能做到这一点?

这是代码:

活动:

    TimePickerFragment newFragmentNight = TimePickerFragment.newInstance(TO_TIME_PICKER_ID);    
    newFragmentNight.show(getSupportFragmentManager(), "timePicker");

对话片段:

public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener
{

private int mId;
private TimePickedListener mListener;

static TimePickerFragment newInstance(int id) {
    Bundle args = new Bundle();
    args.putInt("picker_id", id);
    TimePickerFragment fragment = new TimePickerFragment();
    fragment.setArguments(args);
    return fragment;
}

public Dialog onCreateDialog(Bundle savedInstanceState)
{
// here I don't want to use the current time, I want to use the time passing from the activity
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);

mId = getArguments().getInt("picker_id");


// create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));
}
4

1 回答 1

1

尝试向newInstance()静态方法添加新值并以这种方式捆绑它。它可以像使用构造函数一样传递信息。尝试以下操作:

static TimePickerFragment newInstance(int id, int hour, int minute) 
{
    Bundle args = new Bundle();
    args.putInt("picker_id", id);
    args.putInt("hour", hour);
    args.putInt("minute", minute);
    TimePickerFragment fragment = new TimePickerFragment();
    fragment.setArguments(args);
    return fragment;
}

public Dialog onCreateDialog(Bundle savedInstanceState) 
{
    Bundle args = getArguments();

    final Calendar c = Calendar.getInstance();

    //The second input is a default value in case hour or minute are empty
    int hour = args.getInt("hour", c.get(Calendar.HOUR_OF_DAY));
    int minute = args.getInt("minute", c.get(Calendar.MINUTE));

    mId = getArguments().getInt("picker_id");


    // create a new instance of TimePickerDialog and return it
    return new TimePickerDialog(getActivity(), this, hour, minute, 
                    DateFormat.is24HourFormat(getActivity()));
}

希望这可以帮助。祝你好运!

于 2013-10-25T16:03:52.883 回答