XML布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.com.webviewprogress_demo.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="@+id/path_et"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="wrap_content"
android:singleLine="true"
android:hint="请用户输入网址,直接从www开始即可"
/>
<Button
android:onClick="load"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="加载网页"/>
</LinearLayout>
<ProgressBar
android:id="@+id/webView_pb"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="?android:attr/progressBarStyleHorizontal"
android:max="100"
android:visibility="gone"
/>
<WebView
android:id="@+id/www_wb"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
</WebView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="刷新"
/>
<Button
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="前进"
/>
<Button
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="后退"
/>
</LinearLayout>
</LinearLayout>
代码:
public class MainActivity extends AppCompatActivity {
/**
* 请用户输入网址,直接从www开始即可
*/
private EditText mPathEt;
private ProgressBar mWebprogress;
private WebView mWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initWebView();
initWebSetting();
}
private void initWebView() {
//设置在自己App中打开
mWebView.setWebViewClient(new WebViewClient());
//WebView加载网页的监听 绑定进度条
mWebView.setWebChromeClient(new WebChromeClient(){
@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
mWebprogress.setVisibility(View.VISIBLE);
//设置进度条
mWebprogress.setProgress(newProgress);
if(newProgress == 100) {
mWebprogress.setVisibility(View.GONE);
}
}
});
}
private void initWebSetting() {
mWebView.getSettings().setSupportZoom(true);
}
private void initView() {
mPathEt = (EditText) findViewById(R.id.path_et);
mWebprogress = (ProgressBar) findViewById(R.id.webView_pb);
mWebView = (WebView) findViewById(R.id.www_wb);
}
public void load(View v) {
String s = mPathEt.getText().toString().trim();
mWebView.loadUrl("http://www."+s+".com");
}
}