Dans mon application, j'ai un WebView
qui charge toutes les URL à partir d'Internet. Maintenant, parfois, en raison de réseaux lents, le chargement de la page est long et l'utilisateur ne voit qu'un écran vide.
Je veux montrer un ProgressBar
pendant que le WebView
est chargé et masquer le ProgessBar
lorsque le WebView
est chargé complètement.
Je sais comment utiliser les ProgressBar
et AsyncTask
s, mais voici mon problème.
C'est le code que j'utilise pour charger mon WebView
.
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new HelloWebViewClient());
mWebView.loadUrl(web_URL);
Et ceci ma classe WebViewClient
personnalisée
private class HelloWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
Maintenant, si j'essaie de montrer le ProgressBar
en utilisant AsyncTask
s , alors je suppose que je devrais donner le code pour charger l'URL dans la fonction doInBackGround()
de mon AsyncTask
et afficher la progression via la fonction onProgressUpdate()
.
Mais, comment puis-je charger l'URL à l'intérieur de doInBackground () en tant que doInBackground () s'exécute sur le thread non-UI et je ne pourrai pas utiliser mWebView.loadUrl(web_URL)
à l'intérieur.
Aucune suggestion? Est-ce que je manque quelque chose d'évident? Guidez-moi s'il-vous-plaît.
Vérifiez le code source. Vous aider et résoudre votre problème ...
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);
}
}
Je pense que cela vous aide.
Merci.
Je souhaite afficher une barre de progression pendant que la vue Web est chargée et masquée la barre de progression lorsque la vue Web est complètement chargée.
L'extrait suivant vous aidera.
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");
}
}
passez votre url dans cette méthode
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);
}
si vous voulez afficher la barre de progression chaque fois que l'utilisateur charge une page (et pas seulement le premier chargement), vous pouvez utiliser ceci:
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>
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);
Ajoutez également la méthode:
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);
}
}
@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();
}
}
});
}
Cette solution simple a fonctionné pour moi dansKOTLIN:
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"
}
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();
}
}
});
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();
}
}
});
}