Java Code Examples for android.webkit.WebView

The following examples show how to use android.webkit.WebView. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: SmoothRefreshLayout   Source File: HorizontalScrollCompat.java    License: MIT License 6 votes vote down vote up
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;
}
 
Example 2
Source Project: pe-protector-moe   Source File: TaskAddHtml.java    License: GNU General Public License v3.0 6 votes vote down vote up
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)));
        }
    });
}
 
Example 3
@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);
}
 
Example 4
Source Project: letv   Source File: PointsWeb.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 5
Source Project: rexxar-android   Source File: AlertDialogWidget.java    License: MIT License 6 votes vote down vote up
@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;
}
 
Example 6
@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);
}
 
Example 7
@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;
}
 
Example 8
Source Project: AndroidReview   Source File: WebViewHelper.java    License: GNU General Public License v3.0 6 votes vote down vote up
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;
        }
    });

}
 
Example 9
@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);");
}
 
Example 10
Source Project: remixed-dungeon   Source File: OfflineAds.java    License: GNU General Public License v3.0 6 votes vote down vote up
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);
				}
			}
		});
	}
}
 
Example 11
Source Project: sealtalk-android   Source File: FunctionIntroducedActivity.java    License: MIT License 6 votes vote down vote up
@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);
}
 
Example 12
Source Project: jpHolo   Source File: StartActivity.java    License: MIT License 6 votes vote down vote up
@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");
	}
}
 
Example 13
Source Project: BotLibre   Source File: IssuePreviewActivity.java    License: Eclipse Public License 1.0 6 votes vote down vote up
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;
           }
       });
}
 
Example 14
Source Project: wakao-app   Source File: ActivityAbout.java    License: MIT License 6 votes vote down vote up
@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();
		}
	});
}
 
Example 15
Source Project: Router   Source File: WebActivity.java    License: Apache License 2.0 5 votes vote down vote up
@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");
}
 
Example 16
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;
}
 
Example 17
Source Project: a2cardboard   Source File: SystemWebViewEngine.java    License: Apache License 2.0 5 votes vote down vote up
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");
}
 
Example 18
Source Project: CloudReader   Source File: MyWebViewClient.java    License: Apache License 2.0 5 votes vote down vote up
@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)); //异常放大,缩回去。
    }
}
 
Example 19
Source Project: TikTok   Source File: TestApp.java    License: Apache License 2.0 5 votes vote down vote up
@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);
        }
    });

}
 
Example 20
Source Project: KJFrameForAndroid   Source File: MyBlogBrowser.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 21
Source Project: KlyphMessenger   Source File: WebDialog.java    License: MIT License 5 votes vote down vote up
@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();
    }
}
 
Example 22
/** 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");
}
 
Example 23
Source Project: TigerVideo   Source File: WebPageActivity.java    License: Apache License 2.0 5 votes vote down vote up
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);
    }
 
Example 24
Source Project: Notepad   Source File: WebViewInitState.java    License: Apache License 2.0 5 votes vote down vote up
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;
    }
}
 
Example 25
Source Project: Focus   Source File: MyWebViewClient.java    License: GNU General Public License v3.0 5 votes vote down vote up
@SuppressLint("SetJavaScriptEnabled")
    @Override
    public void onPageFinished(WebView view, String url) {
        view.getSettings().setJavaScriptEnabled(true);
        super.onPageFinished(view, url);
//        view.getSettings().setBlockNetworkImage(false);
        addClickListener(view);//待网页加载完全后设置图片点击的监听方法
    }
 
Example 26
Source Project: BotLibre   Source File: CreateReplyActivity.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@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;
           }
       });
}
 
Example 27
Source Project: wildfly-samples   Source File: CordovaWebViewClient.java    License: MIT License 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 28
Source Project: DeviceConnect-Android   Source File: WebViewActivity.java    License: MIT License 5 votes vote down vote up
@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;
}
 
Example 29
Source Project: keemob   Source File: SystemWebChromeClient.java    License: MIT License 5 votes vote down vote up
/**
 * 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;
}
 
Example 30
Source Project: ByWebView   Source File: ByWebViewClient.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}