【发布时间】:2016-10-30 08:04:05
【问题描述】:
现在我有:-
1) 1 Activity,它是从AppCompactActivity延伸出来的主要Activity。
2) 1 fragment 扩展自 fragment 的类,这是从主要活动调用的片段 (1) - ProfileTeacherActivity.java
3) 1 从DialogFragment 扩展的片段类,从片段(2) - ModalBox.java
所以,基本上,这只是一个简单的执行流程。开始时,应用程序显示main activity (1) 具有抽屉,其中有几个链接作为配置文件链接的示例,当单击此链接时,应用程序调用fragment (2) 显示配置文件的详细信息,并带有一个编辑按钮。单击编辑按钮后,应用程序将调用包含一些EditText 的DialogFragment (3) 来编辑用户的配置文件。
我想要实现的是,在编辑用户的个人资料并成功保存到数据库后,我尝试将用户的数据发送回fragment (2) 只是为了显示最新的更新信息,不幸的是它没有工作。
这是我尝试过的:
1) 在 DialogFragment 中创建接口 (3) - ModalBox.java
public class ModalBox extends DialogFragment{
....
public interface EditProfileModalBoxInterface {
void onFinishEditProfile( HashMap<String, String> dataPassing );
}
...
...
}
2) 在 DialogFragment 内部,我还为 OK 按钮提供了 .setPositiveButton 函数。 - ModalBox.java
public class ModalBox extends DialogFragment{
...
...
public Dialog onCreateDialog(Bundle savedInstanceState ) {
...
builder
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, int id) {
// At here i'm using retrofit2 http library
// to do updating stuff
// and inside success's callback of retrofit2(asynchronous)
// here i call the below function to send data
// dataToSend is a HashMap value
sendBackResultToParent( dataTosend );
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
.....
}
// Function called inside success's callback of retrofit2
public void sendBackResultToParent( HashMap<String, String> data ) {
// instantiated interface
EditProfileModalBoxInterface ls=(EditProfileModalBoxInterface)getTargetFragment();
// declaring interface's method
ls.onFinishEditProfile( data );
}
}
3) 最后,我在 fragment 内部实现了这些接口 (2) - ProfileTeacherActivity.java
public class ProfileTeacherActivity extends Fragment
implements ModalBox.EditProfileModalBoxInterface{
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState ) {
.....
.....
}
// At here the interface's method did't triggered
@Override
public void onFinishEditProfile( HashMap dataPassedFromDialog ) {
Toast.makeText(getActivity(), "Testing...." , Toast.LENGTH_LONG).show();
}
}
我现在感到困惑的是,只有当我在 retrofit2 成功的回调中调用此函数 sendBackResultToParent( dataTosend ); 时才会出现问题,在它之外调用时会触发它。我假设调用的异步导致了这个。如果我可以使用 Promise 或类似的东西,或者有什么解决方法吗?
以下现有解决方案不适用于我的情况:
- Callback to a Fragment from a DialogFragment
- How to send data from DialogFragment to a Fragment?
- Send Data from DialogFragment to Fragment
如果上述用例不够清楚或存在误解,请向我咨询更多意见。感谢您的帮助。问候。
【问题讨论】:
-
不相关,但将片段命名为“ProfileTeacherActivity”有点误导。 :)
-
@TalhaMir 是的,这是我的愚蠢错误。 ;)
标签: java android android-fragments android-dialogfragment asynccallback