将Dialog Fragment中的字符串返回给Activity

时间:2013-02-27 20:08:12

标签: android dialog

我已经阅读了很多这方面的帖子,但我找不到适用于这种情况的任何帖子。

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

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

如果有人可以帮助我,我将非常感激。

谢谢

对话片段

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


    }

1 个答案:

答案 0 :(得分:55)

首选方法是使用回调来获取Fragment的信号。此外,这是Android在Communicating with the 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
    }
}

现在在DialogFragment,当用户点击“确定”按钮时,通过回调将该值发回Activity

public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
    String time = Integer.toString(hourOfDay) + " : " + Integer.toString(minute);
    this.mListener.onComplete(time);
}