Fragment里使用CordovaWebView

来源:互联网 发布:mac下方图标隐藏 编辑:程序博客网 时间:2024/06/10 02: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。

0 0
原创粉丝点击