我有一个班级' Common'和一个碎片' FragmentTest'。 ' Common.java'是一个通用类,它具有一些其他活动的常用功能。这些函数可以通过每个活动的上下文访问..在这里,我将片段的上下文传递给该类中的函数。我这样做
片段: -
Common commonObj = new Common();
commonObj.myfunction(this.getActivity(),"Do you want to Update ?");
在课堂上经过一些操作后,我试图回到片段类。就像这样 : -
public void myfunction(Context context , String str){
//....//
if(context.getClass().isInstance(FragmentTest.class)){
**FragmentTest mContext = (FragmentTest)context;**
mContext.FunctionInFragment();
}
}
但我在这方面有错误。因为我无法将上下文转换为片段引用。 有人请帮忙..
答案 0 :(得分:2)
首先,您无法将# generate sample data
x = np.arange(20)
y1 = np.random.randint(100, size=20)
y2 = np.random.randint(100, size=20)
data = {'A1': pd.DataFrame({'y':y1,'x':x}),
'A2': pd.DataFrame({'y':y2,'x':x})}
p = pd.Panel(data)
# plot panels
df = p.apply(plt.plot)
df.ix[0,0].axes.lines.pop(2)
df.ix[0,0].axes.lines.pop(0)
df.ix[0,0].axes.legend(loc="lower right")
转换为Context
,因为Fragment
不会延伸Fragment
。 Context
确实扩展了Activity
,这就是为什么当您从“活动”中执行此操作时,您正在尝试的工作。
我建议理想情况下Context
课程中的方法应该完全不知道Common
的存在。这样他们就不会“耦合”在一起。为此,您可以使用回调接口。
按如下方式创建Fragment
:
interface
然后,您可以将public interface Callback<T> {
onNext(T result);
}
中的方法更改为以下内容:
Common
然后当您从public void myfunction(Callback<Void> callback , String str){
//....//
callback.onNext(null);
}
调用Common
中的方法时,您会这样做:
Fragment
如果需要将数据发送回函数,则可以更改回调的返回类型。例如,如果你想传回一个字符串,你会使用Common commonObj = new Common();
commonObj.myfunction(
new Callback<Void>() {
@Override
public void onNext(Void result) {
functionInFragment();
}
},
"Do you want to Update ?"
);
,然后原始调用中的方法将如下所示:
Callback<String>
在你的new Callback<String>() {
@Override
public void onNext(String result) {
}
}
课程中你会这样称呼它:
Common
答案 1 :(得分:0)
您可以这样做:
public void myfunction(BaseFragment fragment, String str){
//....//
if(fragment.getClass().isInstance(FragmentTest.class)){
FragmentTest fr = (FragmentTest) fragment;
fr.FunctionInFragment();
}
}
即。使用一些基本片段(BaseFragment)并从中继承。