23

我已经阅读了很多关于这个的帖子,但我找不到任何适用于这个案例的帖子。

我有一个时间选择器对话框,我已将整数值放在一个字符串中,我需要将此字符串恢复为主要活动。

然后,此字符串值将用于设置按钮的文本。

如果有人可以帮助我,将不胜感激。

谢谢

对话片段

public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current time as the default values for the picker
        final Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);

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

    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        // Do something with the time chosen by the user
        String Time =Integer.toString(hourOfDay) + " : " + Integer.toString(minute);
    }
}

代码

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);


        Button btn = (Button) findViewById(R.id.start_time_button);
        Button.setText(Time);


    }
4

1 回答 1

59

首选方法是使用回调从Fragment. 另外,这是 Android 在与 Activity 通信时提出的推荐方法

对于您的示例,在您的 中DialogFragment,添加一个接口并注册它。

public static interface OnCompleteListener {
    public abstract void onComplete(String time);
}

private OnCompleteListener mListener;

// make sure the Activity implemented it
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity); 
    try {
        this.mListener = (OnCompleteListener)activity;
    }
    catch (final ClassCastException e) {
        throw new ClassCastException(activity.toString() + " must implement OnCompleteListener");
    }
}

现在在你的实现这个接口Activity

public class MyActivity extends Activity implements MyDialogFragment.OnCompleteListener {
    //...

    public void onComplete(String time) {
        // After the dialog fragment completes, it calls this callback.
        // use the string here
    }
}

现在在您的 中,当用户单击 OK 按钮时,通过您的回调DialogFragment将该值发送回。Activity

public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
    String time = Integer.toString(hourOfDay) + " : " + Integer.toString(minute);
    this.mListener.onComplete(time);
}
于 2013-02-27T20:16:35.943 回答