Monday, May 25, 2015

Android WebView example

activity_main.xml

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp"
    tools:context=".MainActivity"
    android:background="#ffffb921"
    >
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Load Google.com"
        />
    <!--
        Note that, in order for your Activity to access the
        Internet and load web pages in a WebView, you must add
        the INTERNET permissions to your Android Manifest file:

        <uses-permission android:name="android.permission.INTERNET" />
    -->
    <WebView
        android:id="@+id/wv"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        >
    </WebView>
</LinearLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.webkit.WebView;
import android.app.ActionBar;

public class MainActivity extends Activity{

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

        // Get the application action bar and hide it
        ActionBar ab = getActionBar();
        ab.hide();

        // Get the widgets reference from XML layout
        LinearLayout ll = (LinearLayout) findViewById(R.id.rl);
        final WebView wv = (WebView) findViewById(R.id.wv);
        Button btn = (Button) findViewById(R.id.btn);

        // Set a click listener for Button widget
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /*
                    setWebViewClient(WebViewClient client)
                        Sets the WebViewClient that will receive
                        various notifications and requests.
                 */
                wv.setWebViewClient(new WebViewClient());

                /*
                    loadUrl(String url)
                        Loads the given URL.
                 */
                wv.loadUrl("https://www.google.com/");
            }
        });
    }
}
More android examples