类android.webkit.WebView源码实例Demo

下面列出了怎么用android.webkit.WebView的API类实例代码及写法,或者点击链接到github查看源代码。

public static boolean isScrollingView(View view) {
    if (ViewCatcherUtil.isViewPager(view)
            || view instanceof HorizontalScrollView
            || view instanceof WebView) {
        return true;
    } else if (ViewCatcherUtil.isRecyclerView(view)) {
        RecyclerView recyclerView = (RecyclerView) view;
        RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
        if (manager != null) {
            if (manager instanceof LinearLayoutManager) {
                LinearLayoutManager linearManager = ((LinearLayoutManager) manager);
                return linearManager.getOrientation() == RecyclerView.HORIZONTAL;
            } else if (manager instanceof StaggeredGridLayoutManager) {
                StaggeredGridLayoutManager gridLayoutManager =
                        (StaggeredGridLayoutManager) manager;
                return gridLayoutManager.getOrientation() == RecyclerView.HORIZONTAL;
            }
        }
    }
    return false;
}
 
源代码2 项目: pe-protector-moe   文件: TaskAddHtml.java
public TaskAddHtml(WebView webview, HttpFinishCallBack callBack) {
    this.callBack = callBack;
    List<MapConfigBean> list = LitePal.findAll(MapConfigBean.class);
    List<String> name = new ArrayList<>();
    for (MapConfigBean m : list) {
        name.add(m.name);
    }
    webview.loadUrl("file:///android_asset/html/task.html");
    webview.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            view.loadUrl(String.format("javascript:onLoad(\'%s\')", JSON.toJSONString(name)));
        }
    });
}
 
源代码3 项目: platform-friends-android   文件: WebDialog.java
@SuppressLint("SetJavaScriptEnabled")
private void setUpWebView(int margin) {
    LinearLayout webViewContainer = new LinearLayout(getContext());
    webView = new WebView(getContext());
    webView.setVerticalScrollBarEnabled(false);
    webView.setHorizontalScrollBarEnabled(false);
    webView.setWebViewClient(new DialogWebViewClient());
    webView.getSettings().setJavaScriptEnabled(true);
    webView.loadUrl(url);
    webView.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT));
    webView.setVisibility(View.INVISIBLE);
    webView.getSettings().setSavePassword(false);

    webViewContainer.setPadding(margin, margin, margin, margin);
    webViewContainer.addView(webView);
    webViewContainer.setBackgroundColor(BACKGROUND_GRAY);
    contentFrameLayout.addView(webViewContainer);
}
 
源代码4 项目: letv   文件: PointsWeb.java
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    try {
        if (url.indexOf("?") > 0) {
            String u = url.substring(0, url.indexOf("?"));
            if (TextUtils.isEmpty(u)) {
                return super.shouldOverrideUrlLoading(view, url);
            }
            if (PointsWeb.this.jumpType == 0) {
                if (!".mp4".equals(u.substring(u.lastIndexOf("."), u.length())) || !url.contains("vtype=mp4")) {
                    return super.shouldOverrideUrlLoading(view, url);
                }
                view.stopLoading();
                if (!PointsWeb.this.isFinish) {
                    Intent intent = new Intent("android.intent.action.VIEW");
                    intent.setDataAndType(Uri.parse(url), "video/mp4");
                    intent.putExtra("android.intent.extra.screenOrientation", 0);
                    PointsWeb.this.startActivity(intent);
                }
                return true;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return super.shouldOverrideUrlLoading(view, url);
}
 
源代码5 项目: rexxar-android   文件: AlertDialogWidget.java
@Override
public boolean handle(WebView view, String url) {
    if (TextUtils.isEmpty(url)) {
        return false;
    }
    Uri uri = Uri.parse(url);
    String path = uri.getPath();
    if (TextUtils.equals(path, getPath())) {
        String data = uri.getQueryParameter(KEY);
        Data alertDialogData = null;
        if (!TextUtils.isEmpty(data)) {
            alertDialogData = GsonHelper.getInstance().fromJson(data, Data.class);
        }
        if (null == alertDialogData || !alertDialogData.valid()) {
            return false;
        }

        return renderDialog((Activity) view.getContext(), view, alertDialogData);
    }
    return false;
}
 
源代码6 项目: GankGirl   文件: WebChromeClientConfig.java
@Override
public void onProgressChanged(WebView view, int newProgress) {
    //加载的进度
    progressBar.setProgress(newProgress);
    if (newProgress == 100) {

        Message msg = new Message();
        msg.what = 5;
        handler.sendMessageDelayed(msg, 300);

    } else {

        if (View.GONE == progressBar.getVisibility())
            progressBar.setVisibility(View.VISIBLE);
    }

    super.onProgressChanged(view, newProgress);
}
 
源代码7 项目: mConference-Framework   文件: Register.java
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                            Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    View view = inflater.inflate(R.layout.fragment_register, container, false);

    SharedPreferences sharedPref
            = getActivity().getApplicationContext().getSharedPreferences(PREFERENCES_FILE_NAME, Context.MODE_PRIVATE);

    WebView webview = (WebView)view.findViewById(R.id.web);
    pbar = (ProgressBar)view.findViewById(R.id.loading);
    pbar.setVisibility(View.GONE);
    webview.setWebViewClient(new WebViewClient());
    webview.getSettings().setJavaScriptEnabled(true);

    String registerURL = sharedPref.getString(REGLINK_TAG, null);
    webview.loadUrl(registerURL);

    return view;
}
 
源代码8 项目: AndroidReview   文件: WebViewHelper.java
public static void initWebViewSettings(WebView webView) {
    WebSettings settings = webView.getSettings();
    //这个单位是SP
    settings.setDefaultFontSize(15);

    settings.setJavaScriptEnabled(true);  //支持js

    settings.setUseWideViewPort(false);  //将图片调整到适合webview的大小

    settings.setSupportZoom(true);  //支持缩放

    settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);//无论是否有网络,只要本地有缓存,都使用缓存。本地没有缓存时才从网络上获取。 这里的WebView主要是用来加载图片和解析Html文本

    settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); //支持内容重新布局

    webView.setWebViewClient(new WebViewClient(){
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            //使超链接失效
            return true;
        }
    });

}
 
源代码9 项目: DragonGoApp   文件: GoJsActivity.java
@Override
public void onPageFinished(final WebView view, String url) {
	System.out.println("page finished loading");
	if (curstate!=guistate.review)
		GoJsActivity.viewUrl("javascript:eidogo.autoPlayers[0].last()");
	else if (!Reviews.isNotReviewStage) {
		Reviews.advance();
	}
	if (curstate==guistate.markDeadStones)
		GoJsActivity.viewUrl("javascript:eidogo.autoPlayers[0].detmarkx()");
	final EventManager em = EventManager.getEventManager();
	em.sendEvent(eventType.gobanReady);

	// ask for comments to display them in big
	System.out.println("page finished call detComments");
	GoJsActivity.viewUrl("javascript:eidogo.autoPlayers[0].detComments()");
	// also get the HTML of the page
	GoJsActivity.viewUrl("javascript:console.log('MAGIC'+document.getElementsByTagName('html')[0].innerHTML);");
}
 
源代码10 项目: remixed-dungeon   文件: OfflineAds.java
static void displayBanner() {
	if (BuildConfig.DEBUG) {
		Game.instance().runOnUiThread(new Runnable() {
			@Override
			public void run() {
				LinearLayout layout = Game.instance().getLayout();
				if (layout.getChildCount() == 1) {

					WebView adView = new WebView(Game.instance());

					int adViewHeight = Math.max(50, layout.getHeight() / 10);

					ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, adViewHeight);
					adView.setLayoutParams(params);

					adView.loadDataWithBaseURL(null, Utils.format(adTemplate, "Рекламко"), "text/html", "utf-8", null);
					Game.instance().getLayout().addView(adView, 0);
					Game.setNeedSceneRestart(true);
				}
			}
		});
	}
}
 
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_function_introduced);

    getSupportActionBar().setTitle(R.string.function_introduce);

    mWebView = (WebView) findViewById(R.id.function_introdiced_webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setUseWideViewPort(true);
    mWebView.getSettings().setLoadWithOverviewMode(true);
    mWebView.getSettings().setBuiltInZoomControls(true);
    mWebView.getSettings().setSupportZoom(true);


    MyWebViewClient mMyWebViewClient = new MyWebViewClient();
    mMyWebViewClient.onPageFinished(mWebView, "http://rongcloud.cn/features");
    mMyWebViewClient.shouldOverrideUrlLoading(mWebView, "http://rongcloud.cn/features");
    mMyWebViewClient.onPageFinished(mWebView, "http://rongcloud.cn/features");
    mWebView.setWebViewClient(mMyWebViewClient);
}
 
源代码12 项目: jpHolo   文件: StartActivity.java
@SuppressLint("NewApi")
@Override
public void onCreate(final Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	super.init();
	if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
		if ( 0 != ( getApplicationInfo().flags &= ApplicationInfo.FLAG_DEBUGGABLE ) ) {
			WebView.setWebContentsDebuggingEnabled(true);
		}
	}
	if (checkScreenSize().equals("large") || checkScreenSize().equals("xlarge")) {
		initiateApp("tablet");
	} else {
		initiateApp("smartphone");
	}
}
 
源代码13 项目: BotLibre   文件: IssuePreviewActivity.java
public void resetView() {
       setContentView(R.layout.activity_issue_preview);

	((TextView) findViewById(R.id.title)).setText(Utils.stripTags(title));

       final WebView web = (WebView) findViewById(R.id.detailsLabel);
       web.loadDataWithBaseURL(null, details, "text/html", "utf-8", null);
       web.setWebViewClient(new WebViewClient() {
           public boolean shouldOverrideUrlLoading(WebView view, String url) {
           	try {
           		view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
           	} catch (Exception failed) {
           		return false;
           	}
               return true;
           }
       });
}
 
源代码14 项目: wakao-app   文件: ActivityAbout.java
@SuppressLint("SetJavaScriptEnabled")
private void initView(){
	detail = (WebView) findViewById(R.id.wv_article_detail);
	commentbar = (LinearLayout)findViewById(R.id.comment_bar);
	title = (TextView)findViewById(R.id.top_bar_title);
	toggle_btn = (ImageButton)findViewById(R.id.m_toggle);
	back_btn = (ImageButton)findViewById(R.id.go_back);
	
	
	detail.getSettings().setJavaScriptEnabled(true);
	detail.loadUrl("file:///android_asset/about.html");
	title.setText("关于我们");
	back_btn.setVisibility(View.VISIBLE);
	toggle_btn.setVisibility(View.GONE);
	commentbar.setVisibility(View.GONE);
	
	back_btn.setOnClickListener(new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			onBackPressed();
		}
	});
}
 
源代码15 项目: Router   文件: WebActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_web);

    webView = (WebView) findViewById(R.id.webView);
    webView.loadUrl("file:///android_asset/schame-test.html");
}
 
private static WebView createWebView(Context context) {
    WebView webView = new WebView(context);
    if (SDK_INT < LOLLIPOP) {
        webView.setVisibility(VISIBLE);
    } else {
        webView.setVisibility(INVISIBLE);
    }
    webView.setLayoutParams(new RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    webView.setBackgroundColor(Color.TRANSPARENT);
    prepareWebViewSettings(webView.getSettings());
    return webView;
}
 
源代码17 项目: a2cardboard   文件: SystemWebViewEngine.java
private static void exposeJsInterface(WebView webView, CordovaBridge bridge) {
    if ((Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1)) {
        Log.i(TAG, "Disabled addJavascriptInterface() bridge since Android version is old.");
        // Bug being that Java Strings do not get converted to JS strings automatically.
        // This isn't hard to work-around on the JS side, but it's easier to just
        // use the prompt bridge instead.
        return;            
    }
    SystemExposedJsApi exposedJsApi = new SystemExposedJsApi(bridge);
    webView.addJavascriptInterface(exposedJsApi, "_cordovaNative");
}
 
源代码18 项目: CloudReader   文件: MyWebViewClient.java
@Override
public void onScaleChanged(WebView view, float oldScale, float newScale) {
    super.onScaleChanged(view, oldScale, newScale);
    if (newScale - oldScale > 7) {
        view.setInitialScale((int) (oldScale / newScale * 100)); //异常放大,缩回去。
    }
}
 
源代码19 项目: TikTok   文件: TestApp.java
@Override
public void onCreate() {
    super.onCreate();

    ARouter.openLog();     // 打印日志
    ARouter.openDebug();   // 开启调试模式(如果在InstantRun模式下运行,必须开启调试模式!线上版本需要关闭,否则有安全风险)
    ARouter.init(this); // 尽可能早,推荐在Application中初始化

    RxToast.init(this)
            .setBackgroundColor("#CC000000")
            .setTextColor("#FFFFFF")
            .setGravity(Gravity.CENTER)
            .setPadding(16, 16, 12, 12)
            .setMaxLines(2)
            .setTextSize(12)
            .setZ(30)
            .setMaxLines(3)
            .apply();

    Utils.init(this);
    DoraemonKit.install(this);
    // H5任意门功能需要,非必须
    DoraemonKit.setWebDoorCallback(new WebDoorManager.WebDoorCallback() {
        @Override
        public void overrideUrlLoading(Context context, String s) {
            // 使用自己的H5容器打开这个链接
            WebView webView = new WebView(context);
            webView.loadUrl(s);
        }
    });

}
 
源代码20 项目: KJFrameForAndroid   文件: MyBlogBrowser.java
@Override
public void onReceivedError(WebView view, int errorCode,
        String description, String failingUrl) {
    super.onReceivedError(view, errorCode, description, failingUrl);
    ViewInject.toast("没有找到数据");
    mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
}
 
源代码21 项目: KlyphMessenger   文件: WebDialog.java
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
    Utility.logd(LOG_TAG, "Webview loading URL: " + url);
    super.onPageStarted(view, url, favicon);
    if (!isDetached) {
        spinner.show();
    }
}
 
源代码22 项目: droidkit-webrtc   文件: GAEChannelClient.java
/** Asynchronously open an AppEngine channel. */
@SuppressLint("SetJavaScriptEnabled")
public GAEChannelClient(
    Activity activity, String token, MessageHandler handler) {
  webView = new WebView(activity);
  webView.getSettings().setJavaScriptEnabled(true);
  webView.setWebChromeClient(new WebChromeClient() {  // Purely for debugging.
      public boolean onConsoleMessage (ConsoleMessage msg) {
        Log.d(TAG, "console: " + msg.message() + " at " +
            msg.sourceId() + ":" + msg.lineNumber());
        return false;
      }
    });
  webView.setWebViewClient(new WebViewClient() {  // Purely for debugging.
      public void onReceivedError(
          WebView view, int errorCode, String description,
          String failingUrl) {
        Log.e(TAG, "JS error: " + errorCode + " in " + failingUrl +
            ", desc: " + description);
      }
    });
  proxyingMessageHandler =
      new ProxyingMessageHandler(activity, handler, token);
  webView.addJavascriptInterface(
      proxyingMessageHandler, "androidMessageHandler");
  webView.loadUrl("file:///android_asset/channel.html");
}
 
源代码23 项目: TigerVideo   文件: WebPageActivity.java
private void configWebView() {

        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setLoadsImagesAutomatically(true);
        mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        mWebView.setWebViewClient(mWebViewClient);
        mWebView.setWebChromeClient(mWebChromeClient);
    }
 
源代码24 项目: Notepad   文件: WebViewInitState.java
public void initialize(Context context) {
    if(isInitialized) return;

    SharedPreferences pref = context.getSharedPreferences(context.getPackageName() + "_preferences", Context.MODE_PRIVATE);
    if(pref.getBoolean("markdown", false) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        WebView webView = new WebView(context);
        webView.loadUrl("about:blank");

        isInitialized = true;
    }
}
 
源代码25 项目: Focus   文件: MyWebViewClient.java
@SuppressLint("SetJavaScriptEnabled")
    @Override
    public void onPageFinished(WebView view, String url) {
        view.getSettings().setJavaScriptEnabled(true);
        super.onPageFinished(view, url);
//        view.getSettings().setBlockNetworkImage(false);
        addClickListener(view);//待网页加载完全后设置图片点击的监听方法
    }
 
源代码26 项目: BotLibre   文件: CreateReplyActivity.java
@Override
public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_create_reply);
       
       if (MainActivity.instance instanceof ForumConfig) {
       	HttpGetImageAction.fetchImage(this, MainActivity.instance.avatar, findViewById(R.id.icon));
       } else {
       	((ImageView)findViewById(R.id.icon)).setImageResource(R.drawable.icon,80,80);
       }
       
       TextView text = (TextView) findViewById(R.id.topicText);
       text.setText(MainActivity.post.topic);
       
       CheckBox checkbox = (CheckBox) findViewById(R.id.replyToParentCheckBox);
       if (MainActivity.post.parent != null && MainActivity.post.parent.length() != 0) {
       	checkbox.setChecked(true);
       } else {
       	checkbox.setVisibility(View.GONE);
       }
       
       final WebView web = (WebView) findViewById(R.id.detailsLabel);
       web.loadDataWithBaseURL(null, MainActivity.post.detailsText, "text/html", "utf-8", null);
       
       web.setWebViewClient(new WebViewClient() {
           public boolean shouldOverrideUrlLoading(WebView view, String url) {
           	try {
           		view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
           	} catch (Exception failed) {
           		return false;
           	}
               return true;
           }
       });
}
 
源代码27 项目: wildfly-samples   文件: CordovaWebViewClient.java
/**
 * On received http auth request.
 * The method reacts on all registered authentication tokens. There is one and only one authentication token for any host + realm combination
 *
 * @param view
 * @param handler
 * @param host
 * @param realm
 */
@Override
public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {

    // Get the authentication token
    AuthenticationToken token = this.getAuthenticationToken(host, realm);
    if (token != null) {
        handler.proceed(token.getUserName(), token.getPassword());
    }
    else {
        // Handle 401 like we'd normally do!
        super.onReceivedHttpAuthRequest(view, handler, host, realm);
    }
}
 
源代码28 项目: DeviceConnect-Android   文件: WebViewActivity.java
@Override
public boolean onShowFileChooser(final WebView webView, final ValueCallback<Uri[]> filePathCallback,
                                 final FileChooserParams fileChooserParams) {
    if (mFilePathCallback != null) {
        mFilePathCallback.onReceiveValue(null);
    }
    mFilePathCallback = filePathCallback;

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType(TYPE_IMAGE);
    startActivityForResult(intent, INPUT_FILE_REQUEST_CODE);

    return true;
}
 
源代码29 项目: keemob   文件: SystemWebChromeClient.java
/**
 * Tell the client to display a confirm dialog to the user.
 */
@Override
public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
    dialogsHelper.showConfirm(message, new CordovaDialogsHelper.Result() {
        @Override
        public void gotResult(boolean success, String value) {
            if (success) {
                result.confirm();
            } else {
                result.cancel();
            }
        }
    });
    return true;
}
 
源代码30 项目: ByWebView   文件: ByWebViewClient.java
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
    super.onReceivedError(view, errorCode, description, failingUrl);
    //6.0以下执行
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        return;
    }
    String mErrorUrl = "file:///android_asset/404_error.html";
    view.loadUrl(mErrorUrl);
}
 
 类所在包