如何解决如何从对话框片段到Android中的活动接收数据
我正在从Activity调用DialogFragment以选择状态(DialogFragment中的RecyclerView)。
但是我不确定如何返回选定的状态。
我知道使用Recyclerview,主要任务是将数据从DialogFragment.
发送回上一个活动
从“活动”到“活动”,我可以使用startActivityForResult(intent,code)
,但是从Activity to DialogFragment
来说,我没有。
Activity1 ---> DialogFragment ---> Activity1
任何人都可以帮助我。预先感谢。
解决方法
首选方法是使用回调从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);
}
您可以通过类似的方式使用cal来传递选定的列表值
,您可以在活动中使用界面调用它
公共接口OnChangeListener { void onChange(int state);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。