先来看下webview在一些App当中的应用实例,类似网易 今日头条等新闻类APP中基本都有用到,可以看到顶部栏中间显示的链接是网页链接
接下来我们就来看下webview究竟如何使用
思路:1.我们希望使用当前程序来加载webview页面,而不是通过使用Android系统默认浏览器加载页面。需要实现 setWebViewClient()方法,重写其shouldOverrideUrlLoading(WebView view, String url)方法来实现页面加载
2.实现类似上面导航栏效果,导航栏中间展示网页链接或者网页名称。通过setWebChromeClient()方法,重写 其onReceivedTitle(WebView view, String title)方法
具体代码
配置文件MainActivity.xml
<span style="font-size:14px;"><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <RelativeLayout android:id="@+id/rl_container" android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:id="@+id/btn_return" android:layout_width="wrap_content" android:layout_height="40dip" android:text="@string/title_return" android:layout_alignParentLeft="true"/> <TextView android:id="@+id/tv_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:ellipsize="end"/> <Button android:id="@+id/btn_refresh" android:layout_width="wrap_content" android:layout_height="40dip" android:text="@string/title_refresh" android:layout_alignParentRight="true"/> </RelativeLayout> <WebView android:id="@+id/webView" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/rl_container"/> </RelativeLayout> </span>
MainActivity中
<span style="font-size:14px;">public class MainActivity extends ActionBarActivity { private WebView webView; private Button returnButton,refreshButton; private TextView titleTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); titleTextView= (TextView) findViewById(R.id.tv_title); returnButton= (Button) findViewById(R.id.btn_return); refreshButton= (Button) findViewById(R.id.btn_refresh); webView= (WebView) findViewById(R.id.webView); <span style="color:#ff0000;"> webView.loadUrl("http://www.baidu.com");</span> <span style="color:#ff0000;"> webView.setWebChromeClient(new WebChromeClient()</span>{ @Override public void onReceivedTitle(WebView view, String title) { titleTextView.setText(title); super.onReceivedTitle(view, title); } }); //项目自身调用,而不是采用手机自带浏览器调用 <span style="color:#ff0000;">webView.setWebViewClient(new WebViewClient()</span>{ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return super.shouldOverrideUrlLoading(view, url); } }); returnButton.setOnClickListener(new MyListener()); refreshButton.setOnClickListener(new MyListener()); } class MyListener implements View.OnClickListener { @Override public void onClick(View view) { switch (view.getId()){ case R.id.btn_return: finish(); break; case R.id.btn_refresh: webView.reload(); break; } } } } </span>效果
<uses-permission android:name="android.permission.INTERNET"/>