在我的应用程序中,我有一个WebView
,可以从互联网上加载任何网址。现在,有时由于网络速度慢,页面需要很长时间才能加载,用户只能看到空白屏幕。
我想在加载ProgressBar
时显示WebView
,并在完全加载ProgessBar
时隐藏WebView
。
我知道如何使用ProgressBar
和AsyncTask
,但这是我的问题。
这是我用来加载WebView
的代码。
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new HelloWebViewClient());
mWebView.loadUrl(web_URL);
这是我的自定义WebViewClient
课程
private class HelloWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
现在,如果我尝试使用ProgressBar
显示AsyncTask
,那么我想我必须提供代码来加载{{1}中的网址我的doInBackGround()
的功能,并通过AsyncTask
函数显示进度。
但是,如何在非UI线程上运行 doInBackground(),在doInBackground()中加载URL,我将无法使用{{在它里面。}
有什么建议吗?我错过了一些明显的东西吗请指导我。
答案 0 :(得分:57)
检查源代码。帮助您并解决您的问题...
public class AppWebViewClients extends WebViewClient {
private ProgressBar progressBar;
public AppWebViewClients(ProgressBar progressBar) {
this.progressBar=progressBar;
progressBar.setVisibility(View.VISIBLE);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
}
}
我认为它会对你有所帮助。
感谢。
答案 1 :(得分:21)
我想在webView加载并隐藏时显示progressBar 当webView完全加载时,progessBar。
以下代码段将为您提供帮助。
<强> main.xml中强>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<WebView android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" />
</LinearLayout>
<强> Main.class 强>
public class Main extends Activity {
private WebView webview;
private static final String TAG = "Main";
private ProgressDialog progressBar;
/** Called when the activity is first created. */@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
this.webview = (WebView) findViewById(R.id.webview);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
progressBar = ProgressDialog.show(Main.this, "Showing ProgressDialog", "Loading...");
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.i(TAG, "Processing webview url click...");
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
Log.i(TAG, "Finished loading URL: " + url);
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.e(TAG, "Error: " + description);
Toast.makeText(Main.this, "Oh no! " + description, Toast.LENGTH_SHORT).show();
alertDialog.setTitle("Error");
alertDialog.setMessage(description);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
alertDialog.show();
}
});
webview.loadUrl("http://www.google.com");
}
}
答案 2 :(得分:15)
通过此方法传递您的网址
private void startWebView(String url) {
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
webView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setLoadWithOverviewMode(true);
progressDialog = new ProgressDialog(ContestActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(ContestActivity.this, "Error:" + description, Toast.LENGTH_SHORT).show();
}
});
webView.loadUrl(url);
}
答案 3 :(得分:6)
如果你想在每次用户加载页面时显示进度条(而不仅仅是第一次加载),那么你可以使用它:
MainActivity.java
public class MainActivity extends Activity
{
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
final ProgressDialog progressBar = new ProgressDialog(MainActivity.this);
progressBar.setMessage("Please wait...");
webView.loadUrl("https://example.org/");
webView.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);
if (!progressBar.isShowing()) {
progressBar.show();
}
}
public void onPageFinished(WebView view, String url) {
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
});
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<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="0dp"
android:paddingLeft="0dp"
android:paddingRight="0dp"
android:paddingTop="0dp"
tools:showIn="@layout/activity_main">
<WebView
android:id="@+id/webView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
答案 4 :(得分:5)
String url = "https://stackoverflow.com/questions/11241513/android-progessbar-while-loading-webview";
setProgressBarVisibility(View.VISIBLE);
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
setProgressBarVisibility(View.VISIBLE);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
setProgressBarVisibility(View.GONE);
}
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
setProgressBarVisibility(View.GONE);
}
});
webView.loadUrl(url);
还添加方法:
private void setProgressBarVisibility(int visibility) {
// If a user returns back, a NPE may occur if WebView is still loading a page and then tries to hide a ProgressBar.
if (progressBar != null) {
progressBar.setVisibility(visibility);
}
}
答案 5 :(得分:0)
myThanh.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
progressBar = ProgressDialog.show(MainActivity.this,"Đang tải dữ liệu", "Vui lòng chờ...");
myThanh.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
});
答案 6 :(得分:0)
这个简单的解决方案适用于 KOTLIN :
private fun setupWebView() {
val webViewClient: WebViewClient = object: WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
view?.loadUrl(request?.url.toString())
return super.shouldOverrideUrlLoading(view, request)
}
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
showProgressDialog()
super.onPageStarted(view, url, favicon)
}
override fun onPageFinished(view: WebView?, url: String?) {
hideProgressDialog()
super.onPageFinished(view, url)
}
}
webView.webViewClient = webViewClient
webView.settings.javaScriptEnabled = true
webView.settings.defaultTextEncodingName = "utf-8"
}
答案 7 :(得分:0)
WebView webView;
ProgressDialog progressDialog;
TextView text;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
String message = getIntent().getStringExtra("key").toString();
setTitle(message);
Bundle isNetworkAvailable = getIntent().getExtras();
String value = "file:///android_asset/n/o/i/no_connection.html";
if (isNetworkAvailable()) {
value = isNetworkAvailable.getString("keyHTML");
}
webView = (WebView) findViewById(R.id.kamal);
webView.loadUrl(value);
init();
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private void init() {
webView = (WebView) findViewById(R.id.kamal);
webView.getSettings().setBuiltInZoomControls(true);
webView.setBackgroundColor(0);
webView.getSettings().setJavaScriptEnabled(true);
progressDialog = new ProgressDialog(WebView_Online.this);
progressDialog.setMessage("Loading Please wait...");
progressDialog.setCancelable(false);
progressDialog.show();
webView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
try {
progressDialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
答案 8 :(得分:0)
@SuppressLint("SetJavaScriptEnabled")
private void init() {
webView = (WebView) findViewById(R.id.kamal);
webView.setBackgroundColor(0);
webView.getSettings().setJavaScriptEnabled(true);
progressDialog = new ProgressDialog(WebView_Ofline.this);
progressDialog.setMessage("Loading Please wait...");
progressDialog.setCancelable(false);
progressDialog.show();
webView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
try {
progressDialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
答案 9 :(得分:0)
我尝试在onPageFinished()方法上取得进展,但效果不是很好,呈现Webview会有时间延迟。
尝试使用onPageCommitVisible()更好:
{
"compileOnSave": false,
"compilerOptions": {
"resolveJsonModule": true,
"esModuleInterop": true,
"baseUrl": ".",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"downlevelIteration": true,
"experimentalDecorators": true,
"module": "esnext",
"moduleResolution": "node",
"importHelpers": true,
"target": "es2015",
"typeRoots": ["node_modules/@types"],
"lib": ["es2018", "dom"],
"paths": {
"@scope/name": ["projects/test/src/public_api.ts"]
}
},
"angularCompilerOptions": {
"fullTemplateTypeCheck": true,
"strictInjectionParameters": true
}
}
答案 10 :(得分:0)
将此代码粘贴到您的代码中,然后添加您的URL
var progressDialog: ProgressDialog? = null
private fun startWebView(url: String) {
val settings = webView.getSettings()
settings.setJavaScriptEnabled(true)
webView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY)
webView.getSettings().setBuiltInZoomControls(true)
webView.getSettings().setUseWideViewPort(true)
webView.getSettings().setLoadWithOverviewMode(true)
progressDialog = ProgressDialog(this)
progressDialog!!.setMessage("Loading...")
progressDialog!!.show()
webView.setWebViewClient(object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
view.loadUrl(url)
return true
}
override fun onPageFinished(view: WebView, url: String) {
if (progressDialog!!.isShowing()) {
progressDialog!!.dismiss()
}
}
override fun onReceivedError(view: WebView, errorCode: Int, description: String, failingUrl: String) {
Toast.makeText(this@MainActivity, "Error:$description", Toast.LENGTH_SHORT).show()
}
})
webView.loadUrl(url)
}
答案 11 :(得分:0)
您可以使用类似的东西:
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
super.onPageStarted(view, url, favicon)
binding.pbLoader.visibility = ProgressBar.VISIBLE
}
override fun onPageCommitVisible(view: WebView?, url: String?) {
super.onPageCommitVisible(view, url)
binding.pbLoader.visibility = ProgressBar.GONE
}