Monday, 25 May 2015

Android Load Webview with Progressbar

Here I am going to explain how to display a progress bar with webview
                                  
Step 1) Open res ⇒ layout⇒ activity_main.xml and add below items.
                                    <LinearLayoutxmlns: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:orientation="vertical"

    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin" >
    <WebView
        android:id="@+id/web"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
    </LinearLayout>


Step 2) Activity Class
package com.example.androidprogressbar;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends Activity {

WebView webview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

              final Activity WebActivity = this;
             getWindow().setFeatureInt(Window.FEATURE_PROGRESS,            
                            Window.PROGRESS_VISIBILITY_ON);
             webview= (WebView) findViewById(R.id.web);
             webview.setWebChromeClient(new WebChromeClient() 
             {
              public void onProgressChanged(WebView view, int progress)   
                 {
                     WebActivity .setTitle("Loading...");
                    WebActivity .setProgress(progress * 100); 
                     if(progress == 100)
                    WebActivity .setTitle(R.string.app_name);
           }
         });
     webview.setWebViewClient(new WebViewClient());
     webview.getSettings().setJavaScriptEnabled(true);
     webview.loadUrl("http://google.com");
}
}


Step 3) Add android internet permission to your Manifestfile.xml
 <uses-permission android:name="android.permission.INTERNET"/>


Happy Coding :)