当我尝试MainActivity is not an enclosing class
扩展Fragment类中的Webview时出现错误addJavascriptInterface
:
mXWalkView.addJavascriptInterface(new MainActivity.JS_Bind(this, mXWalkView),"Android");
在我的MainActivity中,我在onCreate方法中以这种方式实现了它:
mXWalkView.addJavascriptInterface(new JS_Bind(this, mXWalkView),"Android");
JS_Bind是MainActivity中的公共类:
public class JS_Bind {
private static final String TAG = "JS_Bind";
private Context context;
private XWalkView mXWalkView;
public JS_Bind(Context c, XWalkView mXWalkView) {
context = c;
this.mXWalkView = mXWalkView;
}
@org.xwalk.core.JavascriptInterface
public void makeToast(String toast) {
Toast mToast = Toast.makeText(context, toast, Toast.LENGTH_SHORT);
mToast.setGravity(Gravity.CENTER, 0, 0);
mToast.show();
}
}
注意:我还使用Crosswalk(Webview库)。如何修复此错误以及它究竟是什么意思?我读了类似的问题和答案,但没有理解。
修改:Fragment
课程:
public class SlideFragment extends Fragment {
private XWalkView mXWalkView;
private Context c;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_demo, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
int position = FragmentPagerItem.getPosition(getArguments());
XWalkPreferences.setValue(XWalkPreferences.REMOTE_DEBUGGING, true);
mXWalkView.addJavascriptInterface(new MainActivity.JS_Bind(this, mXWalkView),"Android");
mXWalkView = (XWalkView) view.findViewById (R.id.webView);
mXWalkView.clearCache(true);
mXWalkView.load(MainActivity.ROOT + "?s=" + getArguments().getString("title") + ".php?page=" + position, null);
答案 0 :(得分:0)
Fragment
无法将this
用作Context
,因为Fragment
不会延伸Context
。在调用JS_Bind
的构造函数时,请使用getActivity()
或getContext()
。
修改
mXWalkView.addJavascriptInterface(new MainActivity.JS_Bind(getActivity(),
mXWalkView), "Android");