WebView
WebView 加载网页的方式
加载网络 URL:
webview.loadUrl("http//...");
加载 assets 下的 HTML 文件:
webview.loadUrl("file://android_asset/test.html");
加载 HTML 代码:
webview.loadData();
或 webview.loadDataWithBaseURL();//推荐使用
网页的前进后退
判断网页是否还有上一级是否还能返回:
webview.canGoBack();
返回上一级:
webview.goBack();
前进(同理):
webview.canGoForward();//是否能前进
webview.goForward();//前进
传参控制前进后退:
webview.canGoBackOrForward(int);//正数是否能前进正数步,负数后退
webview.goBackOrForward(int);//正数前进正数步,负数同理
WebView 网络 URL 使用
1 2 3 4
| <WebView android:id="@+id/webView" android:layout_width="match_parent" android:layout_height="match_parent"/>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| private WebView webView; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_stagger);
webView = findViewById(R.id.webView); webView.loadUrl("https://ruoxijun.github.io/"); webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new MyWebClient());
webView.setWebChromeClient(new MyChromeClient()); }
public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK)&&webView.canGoBack()){ webView.goBack(); return true; } return super.onKeyDown(keyCode, event); }
class MyWebClient extends WebViewClient{ public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { view.loadUrl(request.getUrl().toString()); return true; }
public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); Log.d("webview","网页开始加载"); }
public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); Log.d("webview","网页加载结束"); } }
class MyChromeClient extends WebChromeClient{ public void onProgressChanged(WebView view, int newProgress) { super.onProgressChanged(view, newProgress); }
public void onReceivedTitle(WebView view, String title) { super.onReceivedTitle(view, title); setTitle(title); } }
|