Android中实现Webview顶部带进度条的方法
写这篇文章,做份备忘,简单滴展示一个带进度条的webview示例,进度条位于webview上面.
示例图如下:
主activity代码:
package com.droidyue.demo.webviewprogressbar;
import android.app.activity;
import android.os.bundle;
import android.view.menu;
import android.view.view;
import android.view.view.onclicklistener;
import android.webkit.webchromeclient;
import android.webkit.webview;
import android.widget.progressbar;
import com.droidyue.demo.webviewprogressbar.r;
public class mainactivity extends activity {
@override
protected void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.activity_main);
final progressbar bar = (progressbar)findviewbyid(r.id.myprogressbar);
final webview webview = (webview)findviewbyid(r.id.mywebview);
webview.setwebchromeclient(new webchromeclient() {
@override
public void onprogresschanged(webview view, int newprogress) {
if (newprogress == 100) {
bar.setvisibility(view.invisible);
} else {
if (view.invisible == bar.getvisibility()) {
bar.setvisibility(view.visible);
}
bar.setprogress(newprogress);
}
super.onprogresschanged(view, newprogress);
}
});
findviewbyid(r.id.mybutton).setonclicklistener(new onclicklistener() {
@override
public void onclick(view arg0) {
webview.reload();
}
});
final string url = "http://jb51.net";
webview.loadurl(url);
}
@override
public boolean oncreateoptionsmenu(menu menu) {
getmenuinflater().inflate(r.menu.main, menu);
return true;
}
}
布局文件代码
<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"
android:paddingbottom="@dimen/activity_vertical_margin"
android:paddingleft="@dimen/activity_horizontal_margin"
android:paddingright="@dimen/activity_horizontal_margin"
android:paddingtop="@dimen/activity_vertical_margin"
tools:context=".mainactivity" >
<button
android:id="@+id/mybutton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="reload"
/>
<progressbar
style="?android:attr/progressbarstylehorizontal"
android:id="@+id/myprogressbar"
android:layout_below="@id/mybutton"
android:layout_width="match_parent"
android:layout_height="5px"
/>
<webview
android:id="@+id/mywebview"
android:layout_below="@id/myprogressbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</relativelayout>
不要忘记在mainfest加入使用网络权限哟.
<uses-permission android:name="android.permission.internet"/>
实现很简单,没什么技术含量.备忘而已.
关于如何自定义进度条请参考://www.jb51.net/article/59978.htm