我有一个webview应用程序,其中进度条显示直到从一页导航到另一页时加载页面,但按下后退按钮时不显示。 当按下后退按钮时,页面将从历史记录堆栈中加载。实现back()上的progressbar的任何解决方案。
答案 0 :(得分:0)
您需要使用onBackPressed()
与签入onBackPressed()
相比,webView
可以使用WebView.canGoBack()
转到上一页
-webView.canGoBack()
获取此WebView是否具有后退历史记录项。
如果是,则再次显示
progressBar
否则致电super.onBackPressed();
示例代码
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
WebView webView;
ProgressBar progressBar;
String url = "https://stackoverflow.com/users/7666442/nilesh-rathod?tab=profile";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.web);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.loadUrl(url);
progressBar = (ProgressBar) findViewById(R.id.progressbar);
progressBar.setMax(100);
progressBar.setProgress(1);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(progress);
}
});
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
progressBar.setVisibility(View.GONE);
}
});
}
@Override
public void onBackPressed() {
if(webView.canGoBack()){
webView.goBack();
progressBar.setProgress(1);
progressBar.setVisibility(View.VISIBLE);
}else {
super.onBackPressed();
}
}
}
Layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<WebView
android:id="@+id/web"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ProgressBar
android:layout_marginTop="-7dp"
android:id="@+id/progressbar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="@android:color/transparent"
android:indeterminate="false"
android:max="100"
android:progress="1"/>
</RelativeLayout>