问题
I have a class 'Common' and a fragment 'FragmentTest'. The 'Common.java' is a general class that have some common functions for other activities..Those functions are accessed by context of each activities.. And here I am passing the fragment's context to a function in that class. I am doing like this
In Fragment :-
Common commonObj = new Common();
commonObj.myfunction(this.getActivity(),"Do you want to Update ?");
And in Class after some operation i'm trying to return back to fragment class.Like this :-
public void myfunction(Context context , String str){
//....//
if(context.getClass().isInstance(FragmentTest.class)){
**FragmentTest mContext = (FragmentTest)context;**
mContext.FunctionInFragment();
}
}
But i have error in this..Because i cannot cast the context to fragment reference. Somebody please help..
回答1:
Firstly you can't cast a Context
to a Fragment
as Fragment
doesn't extend Context
. Activity
does extend Context
which is why when you do this from an Activity what you are trying works.
I'd suggest ideally that the methods in your Common
class should be totally unaware of the existence of your Fragment
. This way they are not 'coupled' together. To achieve this you can use a callback interface.
Create an interface
as follows:
public interface Callback<T> {
onNext(T result);
}
Then you can change your method in Common
to the following:
public void myfunction(Callback<Void> callback , String str){
//....//
callback.onNext(null);
}
Then when you call the method in Common
from the Fragment
you would do it like this:
Common commonObj = new Common();
commonObj.myfunction(
new Callback<Void>() {
@Override
public void onNext(Void result) {
functionInFragment();
}
},
"Do you want to Update ?"
);
If you needed to send data back to the function then you can change the return type of the callback. For instance if you wanted to pass back a string you would use Callback<String>
and then the method in the original call would look like this:
new Callback<String>() {
@Override
public void onNext(String result) {
}
}
And in your Common
class you would call it like this:
public void myfunction(Callback<String> callback , String str){
//....//
String result = "Hello from common";
callback.onNext(result);
}
回答2:
You can do something like this:
public void myfunction(BaseFragment fragment, String str){
//....//
if(fragment.getClass().isInstance(FragmentTest.class)){
FragmentTest fr = (FragmentTest) fragment;
fr.FunctionInFragment();
}
}
i.e. using some base fragment(BaseFragment) and inherit from it.
来源:https://stackoverflow.com/questions/43568311/how-do-we-cast-context-to-fragment-reference