我几乎尝试了下面的所有代码,但未显示webview。我知道也有类似的问题,但似乎没有帮助。
这是我的完整代码。
MainActivity.java 这是传递网站网址的地方
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.graphics.Bitmap;
import android.view.View;
import android.widget.ProgressBar;
import com.agrawalsuneet.dotsloader.loaders.AllianceLoader;
public class MainActivity extends AppCompatActivity implements MyWebChromeClient.ProgressListener{
private WebView mWebView;
private ProgressBar mProgressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.webView);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
// add progress bar
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mWebView.setWebChromeClient(new MyWebChromeClient(this));
mWebView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
mProgressBar.setVisibility(View.VISIBLE);
mWebView.loadUrl("http://www.example.com/");
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
mProgressBar.setVisibility(View.GONE);
}
});
}
@Override
public void onUpdateProgress(int progressValue) {
mProgressBar.setProgress(progressValue);
if (progressValue == 100) {
mProgressBar.setVisibility(View.INVISIBLE);
}
}
}
MyWebChromeClient.java 这是用于设置进度条
import android.webkit.WebChromeClient;
import android.webkit.WebView;
public class MyWebChromeClient extends WebChromeClient {
private ProgressListener mListener;
public MyWebChromeClient(ProgressListener listener) {
mListener = listener;
}
@Override
public void onProgressChanged(WebView view, int newProgress) {
mListener.onUpdateProgress(newProgress);
super.onProgressChanged(view, newProgress);
}
public interface ProgressListener {
public void onUpdateProgress(int progressValue);
}
}
activity_main.xml :这是网站布局所在的位置
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/relative_web_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="10dp"
android:progressDrawable="@drawable/bg_progress_bar_webview" />
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/progressBar" />
</RelativeLayout>
我期待的是一个Web视图和一个页面顶部的进度条,该进度条在页面加载时加载(显示进度),而不是仅在页面加载时不显示任何反应。