我已经读了很多关于这方面的文章,但我找不到任何适用于这个案例的文章。
我有一个时间选择器对话框,我已经将整数值放在一个字符串中,我需要将这个字符串返回到主活动中。
该字符串值将用于设置按钮的文本。
如果有人能帮我解决这个问题,我将不胜感激。
谢谢
对话框片段
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);
}
发布于 2013-02-28 04:16:36
首选方法是使用回调从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
中,当用户单击OK按钮时,通过您的回调将该值发送回Activity
。
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
String time = Integer.toString(hourOfDay) + " : " + Integer.toString(minute);
this.mListener.onComplete(time);
}
https://stackoverflow.com/questions/15121373
复制相似问题