Cannot get ProgressDialog to stop after WebView has loaded
I can get th开发者_开发百科e ProgressDialog to show, but I cannot get it to stop after the WebView has been loaded. All I need is a simple refresh button for it.
Here is the working code so far:
public class Quotes extends Activity implements OnClickListener{
WebView webview;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.scroll);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("http://www.dgdevelco.com/quotes/quotesandroid.html");
View refreshClick = findViewById(R.id.refresh);
refreshClick.setOnClickListener(this);
}
public void onClick(View v){
switch(v.getId()){
case R.id.refresh:
ProgressDialog.show(Quotes.this, "", "Loading...", true);
webview.reload();
}
}
}
I just can't figure it out. I've looked everywhere but nothing seems to work.
Right this is the quick answer, you should really implement your own class for the WebViewClient, you should show the dialog in that class as well but you'll figure that out.
First, make your dialog global, (in your real app you might want to pass it in to your client, or declare it in the webviewclient, then override on onPageStarted as well).
ProgressDialog dialog;
then simply:
webview.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
dialog.dismiss();
}
});
public void onClick(View v){
switch(v.getId()){
case R.id.refresh:
dialog = ProgressDialog.show(Quotes.this, "", "Loading...", true);
webview.reload();
}
}
}
This is the API you need: WebViewClient
EDIT
Ok it was annoying me, here is the proper way:
public class Quotes extends Activity implements OnClickListener{
private WebView webview;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.scroll);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new MyWebViewClient(this));
webview.loadUrl("http://www.dgdevelco.com/quotes/quotesandroid.html");
findViewById(R.id.refresh).setOnClickListener(this);
}
public void onClick(View v){
switch(v.getId()){
case R.id.refresh:
webview.reload();
break;
}
}
}
The new class:
public class MyWebViewClient extends WebViewClient {
private Context mContext;
private ProgressDialog mDialog;
public MyWebViewClient(Context context){
mContext = context;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
mDialog = ProgressDialog.show(mContext, "", "Loading...", true);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
mDialog.dismiss();
}
}
精彩评论