Abdul Sadik Yalcin
Abdul Sadik Yalcin

Reputation: 1822

Adding a ProgressBar into Webview - Android

There are similar questions out there but I'm a newbie and getting confused as everybody has a different style of coding... I want a progress bar showing after 'Splash Screen' instead of having a white screen for 10 seconds and each time a link is clicked...

How would I implement this as I have no idea? I am not using a webchromeclient or any other stuff. Still learning. Here are my codes;

ProgressBar in XML;

<ProgressBar
    android:id="@+id/progressBar1"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginLeft="23dp"
    android:layout_marginTop="20dp"
    android:indeterminate="false"
    android:max="100"
    android:minHeight="50dp"
    android:minWidth="200dp"
    android:progress="1" />

My Java code;

public class SecondActivity extends Activity {

 private WebView myWebView;
 private ProgressBar progressBar;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.secondlayout);
    String url = "http://ythaber.com/";

    myWebView = (WebView) this.findViewById(R.id.webView1);
    progressBar = (ProgressBar) findViewById(R.id.progressBar1);

    myWebView.setWebViewClient(new WebViewClient());
    myWebView.getSettings().setJavaScriptEnabled(true);
    myWebView.loadUrl(url);
    myWebView.getSettings().setLoadsImagesAutomatically(true);

}

@Override
// Detect when the back button is pressed
public void onBackPressed() {
    if (myWebView.canGoBack())
        myWebView.goBack();
    else if (myWebView.canGoForward())
        myWebView.goForward();
    }
}

Thanks, DG

Upvotes: 1

Views: 127

Answers (1)

M D
M D

Reputation: 47817

Implement like : onCreate()

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);

setContentView(R.layout.web_view);

web_view = (WebView) findViewById(R.id.web_view);
pd = new ProgressDialog(Activity.this);
pd.setMessage("Please wait Loading...");
pd.show();
web_view.setWebViewClient(new MyWebViewClient());
web_view.setWebViewClient(new WebViewClient());
web_view.getSettings().setJavaScriptEnabled(true);
web_view.getSettings().setLoadsImagesAutomatically(true);
web_view.loadUrl("ur site name");
}

WebViewClient

private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);

if (!pd.isShowing()) {
 pd.show();
}

return true;
}

@Override
public void onPageFinished(WebView view, String url) {
System.out.println("on finish");
if (pd.isShowing()) {
  pd.dismiss();
 }
}

Upvotes: 2

Related Questions