布局文件
<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">
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="2dp"
android:progressDrawable="@drawable/webview_progressbar"
android:visibility="gone" />
</RelativeLayout>
Java代码
public class MainActivity extends AppCompatActivity {
private WebView webView;
private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initWebView();
webView.loadUrl("http://3g.qq.com");
}
private void initView() {
webView = (WebView) findViewById(R.id.webView);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
}
private void initWebView(){
//设置支持JavaScript
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
//应用内打开URL
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
view.loadUrl(String.valueOf(request.getUrl()));
return true;
}
});
//获取网页属性
webView.setWebChromeClient(new WebChromeClient() {
//加载进度
@Override
public void onProgressChanged(WebView view, int newProgress) {
if (newProgress == 100) {
progressBar.setVisibility(View.GONE);
return;
}
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(newProgress);
}
//获取网页标题
@Override
public void onReceivedTitle(WebView view, String title) {
MainActivity.this.setTitle(title);
}
});
}
@Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
return;
}
super.onBackPressed();
}
}
背景文件
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@android:id/background">
<shape>
<corners android:radius="2dp" />
<gradient
android:angle="270"
android:centerColor="#E3E3E3"
android:endColor="#E6E6E6"
android:startColor="#C8C8C8" />
</shape>
</item>
<item android:id="@android:id/progress">
<clip>
<shape>
<corners android:radius="2dp" />
<gradient
android:centerColor="#4AEA2F"
android:endColor="#31CE15"
android:startColor="#5FEC46" />
</shape>
</clip>
</item>
</layer-list>
效果图