中易网

如何在fragment中添加webview

答案:1  悬赏:40  
解决时间 2021-01-15 13:49
  • 提问者网友:川水往事
  • 2021-01-14 20:27
如何在fragment中添加webview
最佳答案
  • 二级知识专家网友:老鼠爱大米
  • 2021-01-14 21:38
因为CordovaWebView 默认的初始化里判断了Content是不是继承CordovaInterface,如果直接使用Fragment继承CordovaInterface,CordovaInterface有个抽象方法getActicity ()和Fragment的相冲突了,并且Fragment的这个同名方法还是final的,无法覆盖。

查看CordovaWebView的源码,它是这样实现的。
public CordovaWebView(Context context, AttributeSet attrs, int defStyle, boolean privateBrowsing) {
super(context, attrs, defStyle, privateBrowsing);
if (CordovaInterface.class.isInstance(context))
{
this.cordova = (CordovaInterface) context;
}
else
{
Log.d(TAG, "Your activity must implement CordovaInterface to work");
}
this.setWebChromeClient(new CordovaChromeClient(this.cordova));
this.initWebViewClient(this.cordova);
this.loadConfiguration();
this.setup();
}

所以只要让CordovaWebView的Content是实现CordovaInterface的接口就可以了。
实现一个类继承接口CordovaInterface:

private class CordovaContext extends ContextWrapper implements CordovaInterface {

Activity activity;
protected final ExecutorService threadPool = Executors.newCachedThreadPool();

public CordovaContext(Activity activity) {
super(activity.getBaseContext());
this.activity = activity;
}

public void startActivityForResult(CordovaPlugin command, Intent intent, int requestCode) {
//activity.startActivityForResult(command, intent, requestCode);
}

public void setActivityResultCallback(CordovaPlugin plugin) {
//activity.setActivityResultCallback(plugin);
}

public Activity getActivity() {
return activity;
}

public Object onMessage(String id, Object data) {
return null;
}

public ExecutorService getThreadPool() {
return threadPool;
}
}

然后在Fragment的onCreateView方法里,更改默认的LayoutInflater inflater的content;
inflater = cloneInContext(new CordovaContext(mActivity);
这样就可以实现Fragment里正常使用CordovaWebView。
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息!
大家都在看
推荐信息