[Android] 获取WebView的页面标题(Title)-----WebChromeClient.onReceivedTitle()方法的重写

应用开发中需要获取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");
			}
		});
	}
}


阅读更多

没有更多推荐了,返回首页