bep*_*ive 5 android casting android-fragments
我有一个类“Common”和一个片段“FragmentTest”。'Common.java' 是一个通用类,它具有其他活动的一些通用函数。这些函数通过每个活动的上下文访问。在这里,我将片段的上下文传递给该类中的一个函数。我这样做
在片段中:-
Common commonObj = new Common();
commonObj.myfunction(this.getActivity(),"Do you want to Update ?");
Run Code Online (Sandbox Code Playgroud)
在一些操作之后,在课堂中,我试图返回片段类。像这样:-
public void myfunction(Context context , String str){
//....//
if(context.getClass().isInstance(FragmentTest.class)){
**FragmentTest mContext = (FragmentTest)context;**
mContext.FunctionInFragment();
}
}
Run Code Online (Sandbox Code Playgroud)
但是我在这方面有错误..因为我无法将上下文转换为片段引用。有人请帮忙..
首先,你不能将 a 转换Context为 a Fragment,因为Fragment它不扩展Context。 Activity确实扩展了Context,这就是为什么当您从活动中执行此操作时,您正在尝试的工作会起作用。
理想情况下,我建议您的Common类中的方法应该完全不知道您的Fragment. 这样它们就不会“耦合”在一起。为了实现这一点,您可以使用回调接口。
创建interface如下:
public interface Callback<T> {
onNext(T result);
}
Run Code Online (Sandbox Code Playgroud)
然后您可以将方法更改Common为以下内容:
public void myfunction(Callback<Void> callback , String str){
//....//
callback.onNext(null);
}
Run Code Online (Sandbox Code Playgroud)
Common然后,当您从中调用该方法时,Fragment您将这样做:
Common commonObj = new Common();
commonObj.myfunction(
new Callback<Void>() {
@Override
public void onNext(Void result) {
functionInFragment();
}
},
"Do you want to Update ?"
);
Run Code Online (Sandbox Code Playgroud)
如果您需要将数据发送回函数,那么您可以更改回调的返回类型。例如,如果您想传回您将使用的字符串Callback<String>,则原始调用中的方法将如下所示:
new Callback<String>() {
@Override
public void onNext(String result) {
}
}
Run Code Online (Sandbox Code Playgroud)
在你的课堂上Common你会这样称呼它:
public void myfunction(Callback<String> callback , String str){
//....//
String result = "Hello from common";
callback.onNext(result);
}
Run Code Online (Sandbox Code Playgroud)