Showing posts with label Android Layouts. Show all posts
Showing posts with label Android Layouts. Show all posts

Tuesday, 3 September 2013

Internet Connection Status & Network Change Receiver example in android

// siddhu vydyabhushana // 9 comments
if you are developing an Android app you may already fetching information from internet. While doing so there is a chance that internet connection is not available on users handset. Hence its always a good idea to check the network state before performing any task that requires internet connection.
You might also want to check what kind of internet connection is available in handset. For example is wifi currently enabled? or is mobile data network is connected.

Check Internet Connection

Here is a simple code snippet that will help you identify what kind of internet connection a user has on her device.
First we need following permission in order to access network state. Add following permission to your AndroidManifest.xml file.
Permissions required to access network state:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Now check following utility class NetworkUtil. It has method getConnectivityStatus which returns an int constant depending on current network connection. If wifi is enabled, this method will return TYPE_WIFI. Similarly for mobile data network is returns TYPE_MOBILE. You got the idea!!
There is also method getConnectivityStatusString which returns current network state as a more readable string.
NetworkUtil.java
package net.viralpatel.network;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class NetworkUtil {
     
    public static int TYPE_WIFI = 1;
    public static int TYPE_MOBILE = 2;
    public static int TYPE_NOT_CONNECTED = 0;
     
     
    public static int getConnectivityStatus(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (null != activeNetwork) {
            if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
                return TYPE_WIFI;
             
            if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
                return TYPE_MOBILE;
        }
        return TYPE_NOT_CONNECTED;
    }
     
    public static String getConnectivityStatusString(Context context) {
        int conn = NetworkUtil.getConnectivityStatus(context);
        String status = null;
        if (conn == NetworkUtil.TYPE_WIFI) {
            status = "Wifi enabled";
        } else if (conn == NetworkUtil.TYPE_MOBILE) {
            status = "Mobile data enabled";
        } else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
            status = "Not connected to Internet";
        }
        return status;
    }
}
You can use this utility class in your android app to check the network state of the device at any moment.
Now this code will return you the current network state whenever the utility method is called. What if you want to do something in your android app when network state changes? Lets say when Wifi is disabled, you need to put your android app service to sleep so that it does not perform certain task. Now this is just one usecase. The idea is to create a hook which gets called whenever network state changes. And you can write your custom code in this hook to handle the change in network state.

Broadcast Receiver to handle changes in Network state

You can easily handle the changes in network state by creating your own Broadcast Receiver. Following is a broadcast receiver class where we handle the changes in network.
Check onReceive() method. This method will be called when state of network changes. Here we are just creating a Toast message and displaying current network state. You can write your custom code in here to handle changes in connection state.
NetworkChangeReceiver.java
package net.viralpatel.network;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class NetworkChangeReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(final Context context, final Intent intent) {
        String status = NetworkUtil.getConnectivityStatusString(context);
        Toast.makeText(context, status, Toast.LENGTH_LONG).show();
    }
}
Once we define our BroadcastReceiver, we need to define the same in AndroidMenifest.xml file. Add following to your menifest file.
<application  ...>
     ...
        <receiver
            android:name="net.viralpatel.network.NetworkChangeReceiver"
            android:label="NetworkChangeReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
        </receiver>
      ...
</application>
We defined our broadcast receiver class in menifest file. Also we defined two intent CONNECTIVITY_CHANGE and WIFI_STATE_CHANGED. Thus this will register our receiver for given intents. Whenever there is change in network state, android will fire these intents and our broadcast receiver will be called.
Below is complete AndroidMenifest.xml file.
AndroidMenifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="net.viralpatel.network"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <receiver
            android:name="net.viralpatel.network.NetworkChangeReceiver"
            android:label="NetworkChangeReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
        </receiver>
    </application>
</manifest>
Run this demo in android emulator or actual device.
When Wifi is enabled, you’ll see a Toast message with message.
                                                 android-network-change-broadcast-wifi-enabled  
Now disable Wifi. The toast message will show you message that internet connection is not available.
                                                android-network-change-broadcast-receiver-not-connected       
Now enable mobile data network. The same will be show in toast message as soon as you enable mobile data connection.
                                                 android-data-connection-broadcast-receiver

Download Source Code

Browse through the source code in following Git repository:
GitHub: https://github.com/viralpatel/android-network-change-detect-example
Download complete source code:
Download: android-network-change-detect-example.zip (376 KB)
Read More

Saturday, 24 August 2013

Android TabActivity Example

// siddhu vydyabhushana // 13 comments
As we know Tab-Activity is now depreciated  in Android, but some time we use it for create simple Tab pages in our application. So today I am going to share tutorial for Tab Host Activity in android. It is a simple tab activity demo, group child activity and pager tab example I will share soon. Hope my blog help you. Please follow step by step my blog for create simple Tab Layout-


Print Screen: 


android tabactivity example
1)Create a new project, name TabHostDemo.
2)Create an  TabHostActivity and extend it to TabActivity.
3)Create 3 other activity name-Homeactivity, AboutActivity, ContactActivity.
4)Create layout activity_tab_host.xml .
5)Create another 3 layout for Home, About, Contact Activity, name activity_home, activity_about, activity_contact.
6)Do optional activity for change tab images on selection.Create ic_tab_home, ic_tab_about, ic_tab_contact.
Note-this step is not must, you can direct put your images in your TabHostActivity-
// Create an Intent to launch an Activity for the tab (to be reused)
intent = new Intent().setClass(this, HomeActivity.class);
spec = tabHost.newTabSpec("home")
.setIndicator("HOME", res.getDrawable(R.drawable.home))//set here
.setContent(intent);
tabHost.addTab(spec);
7)Add images - home.png, about.png, contact.png in drawable download below images-
android tabactivity

android tabactivity

android tabactivity

android tabactivity

android tabactivity

android tabactivity

8)Add activity in manifest.xml
9)Run your project and enjoy :)

import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.widget.TabHost;

public class TabHostActivity extends TabActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab_host);

Resources res = getResources(); // Resource object to get Drawables
TabHost tabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Reusable TabSpec for each tab
Intent intent; // Reusable Intent for each tab

// Create an Intent to launch an Activity for the tab (to be reused)
intent = new Intent().setClass(this, HomeActivity.class);
spec = tabHost.newTabSpec("home")
.setIndicator("HOME", res.getDrawable(R.drawable.ic_tab_home))
.setContent(intent);
tabHost.addTab(spec);

// Do the same for the other tabs

intent = new Intent().setClass(this, AboutActivity.class);
spec = tabHost.newTabSpec("about")
.setIndicator("ABOUT", res.getDrawable(R.drawable.ic_tab_about))
.setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, ContactActivity.class);
spec = tabHost
.newTabSpec("contact")
.setIndicator("CONTACT",
res.getDrawable(R.drawable.ic_tab_contact))
.setContent(intent);
tabHost.addTab(spec);
//set tab which one you want open first time 0 or 1 or 2
tabHost.setCurrentTab(0);
}
}

HomeActivity.java

import android.app.Activity;
import android.os.Bundle;

public class HomeActivity extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
}
}
AboutActivity.java
import android.app.Activity;
import android.os.Bundle;

public class AboutActivity extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
}
}
ContactActivity.java
import android.app.Activity;
import android.os.Bundle;

public class ContactActivity extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact);
}
}
activity_tab_host.xml

   
     

        

        
     
    


Activity_Home.xml


    


activity_about.xml


    
Android Manifest file


    

    
        
            
                

                
            
        
        
             
                  
    


For further files download the zippedfile and enjoyy!!!!!!!! keep smiling and commenting
13) DOWNLOAD ZIP CODE
Please feel free to post your testimonials regarding my work here. Please leave your review by clicking on comment below this post.

Thanks.
Read More

Scroll view Example in android

// siddhu vydyabhushana // 9 comments

Simple Scroll-View example in Android | Vertical Scroll View Demo in Android | Scroll View in Android

Hello Friends, On a specific demand I am going to share very simple code for vertical scroll view in android. Hope it will help you-
scroll view in android

1)MainActivity.java


package com.example.scrollviewdemo;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

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

}

2)activity_main.xml


<RelativeLayout xmlns: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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:src="@drawable/ic_launcher" />

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@+id/imageView1" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <Button
                android:id="@+id/button1"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="Button" />

            <Button
                android:id="@+id/button2"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="Button" />

            <Button
                android:id="@+id/button3"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="Button" />

            <Button
                android:id="@+id/button4"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="Button" />

            <Button
                android:id="@+id/button5"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="Button" />

            <Button
                android:id="@+id/button6"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="Button" />

            <Button
                android:id="@+id/button7"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="Button" />

            <Button
                android:id="@+id/button8"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="Button" />

            <Button
                android:id="@+id/button9"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="Button" />

            <Button
                android:id="@+id/button10"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="Button" />

            <Button
                android:id="@+id/button11"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="Button" />

            <Button
                android:id="@+id/button12"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="Button" />

            <Button
                android:id="@+id/button13"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="Button" />

            <Button
                android:id="@+id/button14"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="Button" />
        </LinearLayout>
    </ScrollView>

</RelativeLayout>

Thanks,
Read More

Thursday, 15 August 2013

Android Beginner: Basic layouts in android

// siddhu vydyabhushana // 8 comments
Understanding layouts is important for good Android application design. In this tutorial, we provide an overview of how layouts fit into the Android application architecture. We also explore some of the specific layout controls available for organizing application screen content in a variety of interesting ways.

What Is A Layout?

Android developers use the term layout to mean one of two things. Both definitions apply to this tutorial, and are, unfortunately used interchangeably in the Android development community. The two definitions of layout are:
  • A type of resource that defines what is drawn on the screen. Layout resources are stored as XML files in the /res/layout resource directory for the application. A layout resource is simply a template for a user interface screen, or portion of a screen, and contain.
  • A type of View class whose primary purpose is to organize other controls. These layout classes (LinearLayout, RelativeLayout, TableLayout, etc. ) are used to display child controls, such as text controls or buttons or images on the screen.
Android user interfaces can be defined as layout resources in XML or created programmatically.

Using Eclipse to Design Layout Resources

The Android Development Plug-in for Eclipse includes a handy layout resource designer for designing and previewing layout resources. The tool includes two tab views: the Layout view allows you to preview how the controls will appear on various screens and for each orientation and the XML view shows you the XML definition of the resource. The layout resource designer is shown in this figure:
Layout figure 1
Here are some tips for working with the layout resource designer in Eclipse:
  • Use the Outline pane to Add and Remove controls to your layout resource.
  • Select a specific control (either in the Preview or the Outline) and use the Property pane to adjust a specific control’s attributes.
  • Use the XML tab to edit the XML definition directly.
It’s important to remember that the Eclipse layout resource designer preview can’t replicate exactly how the layout will appear to end users. For this, you must test your application on a properly configured emulator and, more importantly, on your target devices. Also, certain “complex” controls, including tabs or video viewers, cannot be previewed within Eclipse.

Defining an XML Layout Resource

The most convenient and maintainable way to design application user interfaces is by creating XML layout resources. This method greatly simplifies the UI design process, moving much of the static creation and layout of user interface controls and definition of control attributes, to the XML, instead of littering the code. It creates a potential distinction between UI designers (who concern themselves more with layout) and developers (who know Java and implement application functionality). Developers can still alter the content of a screen programmatically when necessary. Complex controls, like ListView or GridView, are usually populated with data programmatically.
XML layout resources must be stored in the /res/layout project directory (or, in the case of alternative resources, in a specially named sub-directory). It’s common practice to create an XML layout resource for each screen in your application (closely tied to a specific Activity), but this is not required. You could, in theory, create an XML layout resource and use it for different activities, supplying different data on the screen. You can also componentized your layout resources and include them within one another, if needed.
The following is a simple XML layout resource, a template with a LinearLayout containing a TextView and an ImageView, defined in XML:
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     android:gravity="center">  
  7.     <TextView  
  8.         android:layout_width="fill_parent"  
  9.         android:id="@+id/PhotoLabel"  
  10.         android:layout_height="wrap_content"  
  11.         android:text="@string/my_text_label"  
  12.         android:gravity="center_horizontal"  
  13.         android:textSize="20dp" />  
  14.     <ImageView  
  15.         android:layout_width="wrap_content"  
  16.         android:layout_height="wrap_content"  
  17.         android:src="@drawable/matterhorn"  
  18.         android:adjustViewBounds="true"  
  19.         android:scaleType="fitXY"  
  20.         android:maxHeight="250dp"  
  21.         android:maxWidth="250dp"  
  22.         android:id="@+id/Photo" />  
  23. </LinearLayout>  
This layout represents a simple screen with two controls: first some text and then an image below it. These controls are organized within a vertically oriented LinearLayout. The following two figures show what this layout might look like on a device in both portrait and landscape modes:
Layout figure 2
Layout figure 2b
Within the Activity, only a single line of code within the onCreate() method is necessary to load and display a layout resource on the screen. If the layout resource was stored in the /res/layout/main.xml file, that would be:
  1. setContentView(R.layout.main);  

Defining a Layout Programmatically

You can also programmatically create user interface components. For organization and maintainability, this is best left for the odd case rather than the norm. Instead of loading a layout resource directly using the setContentView() method, you must instead build up the screen contents and then supply a parent layout object which contains all the control contents to display as child views to the setContentView() method.
For example, the following code illustrates how to programmatically have an Activity instantiate a LinearLayout view and place two TextView objects within it. No resources whatsoever are used.
  1. public void onCreate(Bundle savedInstanceState) {  
  2.     super.onCreate(savedInstanceState);  
  3.     // setContentView(R.layout.main);  
  4.     TextView label = new TextView(this);  
  5.     label.setText(R.string.my_text_label);  
  6.     label.setTextSize(20);  
  7.     label.setGravity(Gravity.CENTER_HORIZONTAL);  
  8.     ImageView pic = new ImageView(this);  
  9.     pic.setImageResource(R.drawable.matterhorn);  
  10.     pic.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));  
  11.     pic.setAdjustViewBounds(true);  
  12.     pic.setScaleType(ScaleType.FIT_XY);  
  13.     pic.setMaxHeight(250);  
  14.     pic.setMaxWidth(250);  
  15.     LinearLayout ll = new LinearLayout(this);  
  16.     ll.setOrientation(LinearLayout.VERTICAL);  
  17.     ll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));  
  18.     ll.setGravity(Gravity.CENTER);  
  19.     ll.addView(label);  
  20.     ll.addView(pic);  
  21.     setContentView(ll);  
  22. }  
As you can see, the code can rapidly grow in size as more controls are added to the screen, making screen contents more difficult to maintain or reuse.

Exploring Various Layout Types

Now let’s turn our attention to those helpful layout controls that organize other controls. The most commonly used layout classes are:
  • FrameLayout – designed to display a stack of child View controls. Multiple view controls can be added to this layout. This can be used to show multiple controls within the same screen space.
  • LinearLayout – designed to display child View controls in a single row or column. This is a very handy layout method for creating forms.
  • RelativeLayout – designed to display child View controls in relation to each other. For instance, you can set a control to be positioned “above” or “below” or “to the left of” or “to the right of” another control, referred to by its unique identifier. You can also align child View controls relative to the parent edges.
  • TableLayout – designed to organize child View controls into rows and columns. Individual View controls are added within each row of the table using a TableRow layout View (which is basically a horizontally oriented LinearLayout) for each row of the table.
Layout figure 3
Layout figure 3b
Layout figure 3c
Layout figure 3d

Combining Layouts To Organize Controls

A layout (LinearLayout, TableLayout, RelativeLayout, etc.) is a control like any other. This means that layout controls can be nested. For example, you might use a RelativeLayout within a LinearLayout, or vice-versa, in order to organize controls on a screen. The following figure shows a screen with a LinearLayout (parent), a TableLayout (top child)_and a FrameLayout (bottom child).
Layout figure 4
But beware! Keep your screens relatively simple; complex layouts load slowly and cause performance issues.

Providing Alternative Layout Resources

Consider device differences when designing your application layout resources. It is often possible to design flexible layouts that look fine on a variety of different devices, in both portrait and landscape modes. When necessary, you can include alternative layout resources to handle special cases. For example, you could provide different layouts to load depending upon the orientation of the device or whether or not the device has a large screen (e.g. an internet tablet).
For more information on how to use alternative resources, see the Android SDK documentation on Android Resources.

Layout Tools and Optimization

The Android SDK includes several tools that can help design, debug and optimize layout resources. In addition to the layout resource designer built into the Android plug-in for Eclipse, you can use the Hierarchy Viewer and layoutopt tools provided with the Android SDK. These tools are available in the /tools directory of your Android SDK.
You can use the Hierarchy Viewer to inspect layout details at run-time. Find out more about the Hierarchy Viewer on the Android Developer website.
You can use the layoutopt command-line tool to optimize your layout files. Optimizing layouts is important because complicated layout files are slow to load. The layoutopt tool simply scans XML layout files and identifies unnecessary controls. Find out more about the layoutopt tool on the Android Developer website.

Conclusion

Android application user interfaces are defined using layouts. There are a number of different types of layout types that can be used to organize controls on a screen, or portion of a screen. Layouts can be defined using XML resources, or programmatically at run-time in Java. Alternative layouts can be loaded under special circumstances, such as to provide an alternative user interface in portrait versus landscape mode. Finally, designing good layouts is important for application performance; use Android SDK tools like the Hierarchy Viewer and layoutopt to debug and optimize your application layouts.

Read More

Tuesday, 2 July 2013

Android WebView example

// siddhu vydyabhushana // 8 comments
Android’s WebView allows you to open an own windows for viewing URL or custom html markup page.
In this tutorial, you will create two pages, a page with a single button, when you clicked on it, it will navigate to another page and display URL “google.com” in WebView component.
P.S This project is developed in Eclipse 3.7, and tested with Android 2.3.3.

1. Android Layout Files

Create two Android layout files – “res/layout/main.xml” and “res/layout/webview.xml“.
File : res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <Button
        android:id="@+id/buttonUrl"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Go to http://www.google.com" />
 
</LinearLayout>
File : res/layout/main.xml – WebView example
<?xml version="1.0" encoding="utf-8"?>
<WebView  xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/webView1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
/>

2. Activity

Two activity classes, an activity to display a button, another activity display the WebView with predefined URL.
File : MainActivity.java
package com.mkyong.android;
 
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
 
public class MainActivity extends Activity {
 
	private Button button;
 
	public void onCreate(Bundle savedInstanceState) {
		final Context context = this;
 
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
 
		button = (Button) findViewById(R.id.buttonUrl);
 
		button.setOnClickListener(new OnClickListener() {
 
		  @Override
		  public void onClick(View arg0) {
		    Intent intent = new Intent(context, WebViewActivity.class);
		    startActivity(intent);
		  }
 
		});
 
	}
 
}
File : WebViewActivity.java
package com.mkyong.android;
 
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
 
public class WebViewActivity extends Activity {
 
	private WebView webView;
 
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.webview);
 
		webView = (WebView) findViewById(R.id.webView1);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.loadUrl("http://www.google.com");
 
	}
 
}

3. Android Manifest

WebView required INTERNET permission, add below into AndroidManifest.xml.
<uses-permission android:name="android.permission.INTERNET" />
File : AndroidManifest.xml – See full example.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mkyong.android"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk android:minSdkVersion="10" />
 
    <uses-permission android:name="android.permission.INTERNET" />
 
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".WebViewActivity"
            android:theme="@android:style/Theme.NoTitleBar" />
 
        <activity
            android:label="@string/app_name"
            android:name=".MainActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>

4. Demo

By default, just display a button.
android webview example
Click on button, WebView is display.
android webview example

5. Demo, Again

WebView allow you to manually load custom HTML markup, via webView.loadData(), see modified version :
package com.mkyong.android;
 
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
 
public class WebViewActivity extends Activity {
 
	private WebView webView;
 
	public void onCreate(Bundle savedInstanceState) {
	   super.onCreate(savedInstanceState);
	   setContentView(R.layout.webview);
 
	   webView = (WebView) findViewById(R.id.webView1);
	   webView.getSettings().setJavaScriptEnabled(true);
	   //webView.loadUrl("http://www.google.com");
 
	   String customHtml = "<html><body><h1>Hello, WebView</h1></body></html>";
	   webView.loadData(customHtml, "text/html", "UTF-8");
 
	}
 
}
Now, when button is clicked, a custom html page is displayed.
android webview example

Download Source Code

Download it – Android-WebView-Example.zip (16 KB)
Read More

Android GridView example

// siddhu vydyabhushana // 10 comments
In Android, GridView let you arranges components in a two-dimensional scrolling grid. For detail attribute exaplanation, see GridView reference.
In this tutorial, we will show you 2 common GridView examples :
  1. Normal way, just display text in GridView layout.
  2. Create a custom adapter to display image and text in GridView layout.
P.S This project is developed in Eclipse 3.7, and tested with Android 2.3.3.

1. Normal GridView example

Display characters from A to Z in GridView layout. Quite simple, it should be sef-explanatory.
1.1 Android Layout file – res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gridView1"
    android:numColumns="auto_fit"
    android:gravity="center"
    android:columnWidth="50dp"
    android:stretchMode="columnWidth"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
 
</GridView>
1.2 Activity
package com.mkyong.android;
 
import android.app.Activity;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
 
public class GridViewActivity extends Activity {
 
	GridView gridView;
 
	static final String[] numbers = new String[] { 
			"A", "B", "C", "D", "E",
			"F", "G", "H", "I", "J",
			"K", "L", "M", "N", "O",
			"P", "Q", "R", "S", "T",
			"U", "V", "W", "X", "Y", "Z"};
 
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
 
		setContentView(R.layout.main);
 
		gridView = (GridView) findViewById(R.id.gridView1);
 
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, numbers);
 
		gridView.setAdapter(adapter);
 
		gridView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v,
				int position, long id) {
			   Toast.makeText(getApplicationContext(),
				((TextView) v).getText(), Toast.LENGTH_SHORT).show();
			}
		});
 
	}
 
}
1.3 Demo
android grid view example

2. Custom Adapter example

In this example, extend a BaseAdapter to display a group of image and text in GridView layout.
2.1 Two Android Layout files
File – res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gridView1"
    android:numColumns="auto_fit"
    android:gravity="center"
    android:columnWidth="100dp"
    android:stretchMode="columnWidth"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
 
</GridView>
File – res/layout/mobile.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="5dp" >
 
    <ImageView
        android:id="@+id/grid_item_image"
        android:layout_width="50px"
        android:layout_height="50px"
        android:layout_marginRight="10px"
        android:src="@drawable/android_logo" >
    </ImageView>
 
    <TextView
        android:id="@+id/grid_item_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@+id/label"
        android:layout_marginTop="5px"
        android:textSize="15px" >
    </TextView>
 
</LinearLayout>
2.2 Custom Adapter
package com.mkyong.android.adapter;
 
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
 
import com.mkyong.android.R;
 
public class ImageAdapter extends BaseAdapter {
	private Context context;
	private final String[] mobileValues;
 
	public ImageAdapter(Context context, String[] mobileValues) {
		this.context = context;
		this.mobileValues = mobileValues;
	}
 
	public View getView(int position, View convertView, ViewGroup parent) {
 
		LayoutInflater inflater = (LayoutInflater) context
			.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 
		View gridView;
 
		if (convertView == null) {
 
			gridView = new View(context);
 
			// get layout from mobile.xml
			gridView = inflater.inflate(R.layout.mobile, null);
 
			// set value into textview
			TextView textView = (TextView) gridView
					.findViewById(R.id.grid_item_label);
			textView.setText(mobileValues[position]);
 
			// set image based on selected text
			ImageView imageView = (ImageView) gridView
					.findViewById(R.id.grid_item_image);
 
			String mobile = mobileValues[position];
 
			if (mobile.equals("Windows")) {
				imageView.setImageResource(R.drawable.windows_logo);
			} else if (mobile.equals("iOS")) {
				imageView.setImageResource(R.drawable.ios_logo);
			} else if (mobile.equals("Blackberry")) {
				imageView.setImageResource(R.drawable.blackberry_logo);
			} else {
				imageView.setImageResource(R.drawable.android_logo);
			}
 
		} else {
			gridView = (View) convertView;
		}
 
		return gridView;
	}
 
	@Override
	public int getCount() {
		return mobileValues.length;
	}
 
	@Override
	public Object getItem(int position) {
		return null;
	}
 
	@Override
	public long getItemId(int position) {
		return 0;
	}
 
}
2.3 Activity
package com.mkyong.android;
 
import com.mkyong.android.adapter.ImageAdapter;
import android.app.Activity;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
 
public class GridViewActivity extends Activity {
 
	GridView gridView;
 
	static final String[] MOBILE_OS = new String[] { 
		"Android", "iOS","Windows", "Blackberry" };
 
	@Override
	public void onCreate(Bundle savedInstanceState) {
 
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
 
		gridView = (GridView) findViewById(R.id.gridView1);
 
		gridView.setAdapter(new ImageAdapter(this, MOBILE_OS));
 
		gridView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {
				Toast.makeText(
				   getApplicationContext(),
				   ((TextView) v.findViewById(R.id.grid_item_label))
				   .getText(), Toast.LENGTH_SHORT).show();
 
			}
		});
 
	}
 
}
2.4 Demo
android gridview custom adapter example

Download Source Code

Download it – Android-GridView-Example.zip (21 KB)
Read More