首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将对话框片段中的字符串返回给Activity

将对话框片段中的字符串返回给Activity
EN

Stack Overflow用户
提问于 2013-02-28 04:08:12
回答 1查看 28.1K关注 0票数 23

我已经读了很多关于这方面的文章,但我找不到任何适用于这个案例的文章。

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

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

如果有人能帮我解决这个问题,我将不胜感激。

谢谢

对话框片段

代码语言:javascript
复制
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);
    }
}

代码

代码语言:javascript
复制
@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);


    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-02-28 04:16:36

首选方法是使用回调从Fragment获取信号。这也是Android在Communicating with the Activity上推荐的方法。

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

代码语言:javascript
复制
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中实现这个接口

代码语言:javascript
复制
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中,当用户单击OK按钮时,通过您的回调将该值发送回Activity

代码语言:javascript
复制
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
    String time = Integer.toString(hourOfDay) + " : " + Integer.toString(minute);
    this.mListener.onComplete(time);
}
票数 59
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15121373

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档