Fragment裏使用CordovaWebView

因爲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。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章