将值传递给TimePickerFragment

时间:2013-10-25 15:57:38

标签: android dialogfragment

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

这是代码:

的活动:

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

DialogFragment:

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()));
}

1 个答案:

答案 0 :(得分: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()));
}

希望这会有所帮助。祝你好运!