作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我已经阅读了很多关于此的帖子,但我找不到任何适用于此案例的帖子。
我有一个时间选择器对话框,我已将整数值放在一个字符串中,我需要将此字符串返回到主要 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
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/
到目前为止,我已经生成了以下代码来尝试将相关数据整合在一起。 但是,使用“+ 7”函数会产生以下问题。 Registration date = '2018-01-01' 它正在推迟 2018-04-0
我已经成功地将我的自定义购物车发布到 PayPal——它处理订单非常漂亮,当收到付款时,它会将数据发回我在配置中指定的 URL。代码基于此处找到的库:http://www.phpfour.com/bl
我是一名优秀的程序员,十分优秀!