Thursday, July 24, 2014

Use ImageButton Selector In Android

In the last tutorial, we saw how to use “ImageButton” to display a “Button” with a customized background image. But that's not all, we can use more than just a simple image. Android allows us to change the button’s background depending on the different states like default, focused or pressed. We shall learn how to use this feature in this tutorial.

1. Add Images to Resources

We shall choose 3 images for the 3 button states, and put them into “res/drawable” folder. For illustration purpose, we are using three kinds of tennis balls as the button backgrounds.

button_normal_green.png – Default image button.
button_focused_orange.png – Displayed when the button is focused, for example, when phone’s keypad is moved on to this button.
button_pressed_red.png – Displayed when the button is pressed.

2. Add Selector for different button states

Now, we shall create a new XML file in “res/drawable/” folder and name it suitably. In this case, we shall just name it as “new_button.xml“. This file defines which button state corresponds to which image.
This button can now be referenced with the Id : @drawable/new_button.

File : res/drawable/new_button.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/button_pressed_red"
android:state_pressed="true" />
<item android:drawable="@drawable/button_focused_orange"
      android:state_focused="true" />
<item android:drawable="@drawable/button_normal_green"/>
</selector>

3. Add Button

Open the “res/layout/main.xml” file, and add a normal button. Attach the above background image to this button by specifying the attribute “android:background="@drawable/new_button”

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:gravity="center"
    android:orientation="vertical" >
  
<Button       android:id="@+id/imageButtonSelector"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/new_button" />
</LinearLayout>

4. Java Code

In the Main.java file, we shall add a simple click listener to the normal button.

File : Main.java

package com.endeavour.ImgBtnSelector;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnClickListener;
public class Main extends Activity {
                Button imageButton;
                @Override
                public void onCreate(Bundle savedInstanceState) {
                       super.onCreate(savedInstanceState);
                       setContentView(R.layout.main);
                       addListenerOnButton();
                }
                public void addListenerOnButton() {
                imageButton = (Button) findViewById(R.id.imageButtonSelector);
                imageButton.setOnClickListener(new OnClickListener() {
                      @Override
                      public void onClick(View arg0) {
                      Toast.makeText(HomeScreen.this,"ImageButton(selector) is clicked!", Toast.LENGTH_SHORT).show();
                      }
               });
         }
 }

5. Output

Running the app shall yield the following result:

i. Default button: Green


ii. Focussed : Orange


iii. Pressed: Red


Wednesday, July 23, 2014

Use Image Button in Android

It happens many a times that we wish to use an image as a button in our Android app to enhance the user aesthetics. An easy way to do this is to use the Image Button. We can use “android.widget.ImageButton” to display a normal “Button“, with a customized background image for the button.

In this tutorial, we shall learn how to display a button with a background image named “imgbtn.png“. When a user clicks on it, a short toast message is displayed.

Note: We can also use ImageButton selector which allows to change a button’s images depending on whether the button is pressed or not. We shall see this in the next tutorial.

1. Add Image to Resources

Put the image you wish to use as the button background into “res/drawable-hdpi” folder, in our case "imgbtn.png".

2. Add ImageButton

Open the “res/layout/main.xml” file, add an “ImageButton” tag, and define the background image via “android:src“.

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:gravity="center"
android:orientation="vertical" >   <ImageButton android:id="@+id/imageButton1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/imgbtn" />   </LinearLayout>

3. Java Code

The Java code should look like this. Add a click listener on the image button.

File : Main.java

package com.endeavour.imagebuttontutorial;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageButton;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnClickListener;
public class Main extends Activity {
       ImageButton imageButton;
       @Override
       public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.main);
              addListenerOnButton();
       }
       public void addListenerOnButton() {
              imageButton = (ImageButton) findViewById(R.id.imageButton1);
              imageButton.setOnClickListener(new OnClickListener() {
                     @Override
                     public void onClick(View arg0) {
                        Toast.makeText(HomeScreen.this,"ImageButton is clicked!", Toast.LENGTH_SHORT).show();
                     }
              });
       }
}

4. Output

Run the program. The following output shall be produced, depending on the image that you have selected.

i. Image Button




ii. When Image Button is pressed



Friday, July 18, 2014

Use Button in Android

Button plays a very important role in app development. It would be next to impossible to design an app without using a button. Let's have a look at this important component in this post.
In this tutorial, we shall learn how to display a normal button, add a click listener and open a URL in your Android’s internet browser, when a user clicks on the button.

1. Add Button

Let us first add the button in the layout file. Open “res/layout/main.xml” file, and add a button.
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:gravity="center"
    android:orientation="vertical" >
   
<Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Go to mobilitytutorials blog" />
</LinearLayout>

2. Code

We shall attach a click listener to the button so that when a user clicks on it, mobile browser is opened and the URL: "http://mobilitytutorials.blogspot.in" is displayed.
File : MainActivity.java

package com.endeavour.buttontutorial;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
       Button button;
       @Override
       public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.main);
              addListenerOnButton();
       }
       public void addListenerOnButton(){
              button = (Button)findViewById(R.id.button1);
              button.setOnClickListener(new OnClickListener() {
                     @Override
                     public void onClick(View arg0) {
                       Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://mobilitytutorials.blogspot.in/p/index.html"));
                       startActivity(browserIntent);
      }
    });
  }
}

3. Output

The following output shall be displayed:

1. Button on the home screen


2. Clicking the button takes you to the stated URL.

Monday, July 14, 2014

Grid View

In Android, GridView lets you arrange screen elements in a two-dimensional scrolling grid. The grid items are automatically inserted to the layout using a ListAdapter.
In this tutorial, we shall see 2 common GridView examples :
1. Basic way to display text in GridView layout.
2. Create a custom adapter to display images as well as text in GridView layout.

1. Normal GridView example

i. Layout
Display characters from A to Z in GridView layout. Write the following code in your activity_main.xml layout file.
Android Layout file – res/layout/activity_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>

ii. Activity
Write the following Java code in MainActivity.java file in your src folder.
File: src/com.endeavour.android/MainActivity.java

package com.endeavour.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 MainActivity 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.activity_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();
                       }
               });

        }

}

iii. Output

The following output shall be displayed on your screen.







2. Custom Adapter 

In this example, we shall extend a BaseAdapter to display a group of image and text in GridView layout.
i. Layout
We shall need two layout files for this purpose

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/fruit.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="50dp"
        android:layout_height="50dp"
        android:layout_marginRight="10dp"
        android:src="@drawable/apple" >
    </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="5dp"
        android:textSize="15dp" >
    </TextView>

</LinearLayout>

ii. Custom Adapter

Create a custom adapter.
File: 


src/com.endeavour.android/ImageAdapter.java


package com.endeavour.android;

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;


public class ImageAdapter extends BaseAdapter {
        private Context context;
        private final String[] fruitValues;

        public ImageAdapter(Context context, String[] fruitValues) {
               this.context = context;
               this.fruitValues = fruitValues;
        }

        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 fruit.xml
                       gridView = inflater.inflate(R.layout.fruit, null);

                       // set value into textview
                       TextView textView = (TextView) gridView
                                      .findViewById(R.id.grid_item_label);
                       textView.setText(fruitValues[position]);

                       // set image based on selected text
                       ImageView imageView = (ImageView) gridView
                                      .findViewById(R.id.grid_item_image);

                       String mobile = fruitValues[position];

                       if (mobile.equals("Apple")) {
                               imageView.setImageResource(R.drawable.apple);
                       } else if (mobile.equals("Banana")) {
                               imageView.setImageResource(R.drawable.banana);
                       } else if (mobile.equals("Mango")) {
                               imageView.setImageResource(R.drawable.mango);
                       } else {
                               imageView.setImageResource(R.drawable.orange);
                       }

               } else {
                       gridView = (View) convertView;
               }

               return gridView;
        }

        @Override
        public int getCount() {
               return fruitValues.length;
        }

        @Override
        public Object getItem(int position) {
               return null;
        }

        @Override
        public long getItemId(int position) {
               return 0;
        }

}

iii. Activity

File: src/com.endeavour.android/MainActivity.java



package com.endeavour.android;

import com.example.android.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 MainActivity extends Activity {

        GridView gridView;

        static final String[] Fruit = new String[] {
               "Apple", "Banana", "Mango", "Orange" };

        @Override
        public void onCreate(Bundle savedInstanceState) {

               super.onCreate(savedInstanceState);
               setContentView(R.layout.main);

               gridView = (GridView) findViewById(R.id.gridView1);

               gridView.setAdapter(new ImageAdapter(this, Fruit));

               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();

                       }
               });

        }

}

iv. Output

The following output shall be displayed.