gpt4 book ai didi

android - 将字符串从对话框 fragment 返回到 Activity

转载 作者:IT老高 更新时间:2023-10-28 22:24:20 25 4
gpt4 key购买 nike

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

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

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

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

谢谢

对话框 fragment

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


}

最佳答案

首选方法是使用回调从 Fragment 获取信号。此外,这是 Android 在 Communicating with the Activity 提出的推荐方法

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

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

中实现这个 接口(interface)
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

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

关于android - 将字符串从对话框 fragment 返回到 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15121373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com