Hello, I want to add a progress bar in my webview
.
I saw a tutorial and it did not work properly, because the progress bar is loading forever.
I will post the code as it was, I wanted the progress bar to appear only when loading the page, code I have:
public class MainActivity extends Activity {
private ProgressBar pb;
private WebView wv;
private String URL = "http://www.google.com.br";
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getActionBar();
actionBar.hide();
wv = (WebView) findViewById(R.id.webView1);
pb = (ProgressBar)findViewById(R.id.progressBar1);
carregarSite();
}
public void carregarSite() {
try {
// Verifica conexão
if (verificaConexao()) {
// Ajusta algumas configurações
WebSettings ws = wv.getSettings();
ws.setJavaScriptEnabled(true);
ws.setBuiltInZoomControls(true);
wv.setWebViewClient(new WebViewClient());
wv.setWebChromeClient(new WebChromeClient());
wv.loadUrl(URL);
}
else
msgConexao();
} catch (Exception e) {
Toast.makeText(MainActivity.this, "Erro ao carregar o site", 1000)
.show();
}
}
@Override
public void onBackPressed() {
msgExit();
}
private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
pb.setVisibility(View.GONE);
super.onPageFinished(view, url);
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if((keyCode == KeyEvent.KEYCODE_BACK) && wv.canGoBack())
{
wv.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:ignore="MergeRootFrame" >
<WebView
android:id="@+id/webView1"
android:layout_width="match_parent"
android:layout_height="357dp"
android:layout_weight="1.78" />
<ProgressBar
android:id="@+id/progressBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
/>
</LinearLayout>