[Android] 獲取WebView的頁面標題(Title)-----WebChromeClient.onReceivedTitle()方法的重寫
阿新 • • 發佈:2019-01-02
應用開發中需要獲取WebView當前頁面的標題,可能通過對WebChromeClient.onReceivedTitle()方法的重寫來實現
效果圖如下:
程式碼如下:
public class MainActivity extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_layout); final TextView txtTitle = (TextView) findViewById(R.id.txtTitle); final WebView webView = (WebView)findViewById(R.id.btnWebView); WebChromeClient wvcc = new WebChromeClient() { @Override public void onReceivedTitle(WebView view, String title) { super.onReceivedTitle(view, title); Log.d("ANDROID_LAB", "TITLE=" + title); txtTitle.setText("ReceivedTitle:" +title); } }; // 設定setWebChromeClient物件 webView.setWebChromeClient(wvcc); // 建立WebViewClient物件 WebViewClient wvc = new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // 使用自己的WebView元件來響應Url載入事件,而不是使用預設瀏覽器器載入頁面 webView.loadUrl(url); // 消耗掉這個事件。Android中返回True的即到此為止吧,事件就會不會冒泡傳遞了,我們稱之為消耗掉 return true; } }; webView.setWebViewClient(wvc); final Button btnLoadWeb = (Button)findViewById(R.id.btnLoadWeb); btnLoadWeb.setOnClickListener(new Button.OnClickListener(){ public void onClick(View v){ webView.loadUrl("http://www.baidu.com"); } }); } }