應用開發中需要獲取WebView當前頁面的標題,可能通過對WebChromeClient.onReceivedTitle()方法的重寫來實現
效果圖如下:
代碼如下:vcD4KPHA+PHByZSBjbGFzcz0=”brush:java;”>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(“https://www.baidu.com”);
}
});
}
}