Custom GridView Android

GridView is used to display items in a two-dimensional, scrollable grid form. The grid items are automatically inserted to the layout using a Adapter.

For example,  displaying grid of icons. Item is represented by a single item view. This pattern is quite handy as it shows several icons on screen at the same time. Its helps displaying grids of data in a very simple and scrollable grid manner.

The simplest way to display a grid view is using ArrayAdapter class . You can find the gridview arrayadapter example here.

We can also create our own custom adapters using BaseAdapter class. Custom Adapters are way better than array adapters, they give you more control over the list/grid view content and UI .Here we inflate each row of GridView using a layout.

The following example explains the usage of ListView using a custom adapter.

Step1: Create the xml for the activity which contains a ListView

 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"
tools:context=".GridViewActivity" >

<GridView
android:id="@+id/grid_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:numColumns="3" >
</GridView>

</RelativeLayout>

Step 2: Create a custom layout for each row of the Grid View.

 grid_item.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:orientation="vertical" >

    <ImageView
        android:id="@+id/imgView_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/ic_launcher"/>

    <TextView
        android:id="@+id/textView_id"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal" />

</LinearLayout>

Step 3: Create a custom adapter in the following way .

GridAdapter.java 

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class GridAdapter extends BaseAdapter {

	String[] textArray;
	Context contxt;

	public GridAdapter(String[] textArr, Context context) {
		textArray = textArr;
		contxt=context;
	}

	@Override
	public int getCount() {

		return textArray.length;
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		// create a new LayoutInflater
		LayoutInflater inflater = (LayoutInflater) contxt
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		View gridView;
		gridView = null;
		convertView = null;// avoids recycling of grid view
		if (convertView == null) {

			gridView = new View(contxt);
			// inflating grid view item
			gridView = inflater.inflate(R.layout.grid_item, null);

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

		}

		return gridView;
	}

}

Step 4: Create the Activity and implement custom adapter in the activity using the code mentioned below.

  • Create  GridAdapter type adapter .
  • Set GridView adapter as this custom adapter.
  • You can set listeners on your list view also.

GridViewActivity.java

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

import com.example.customgridviewexample.R;

public class GridViewActivity extends Activity {
	static final String[] numbers = new String[] { "one", "two", "three",
			"four", "five", "six", "seven", "eight", "nine", "ten", "eleven",
			"twelve", "thirteen", "fourteen", "fifteen", "sixteen",
			"seventeen", "eighteen", "nineteen", "twenty", "twenty one",
			"twenty two" };
	GridView gridView;
	GridAdapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		gridView = (GridView) findViewById(R.id.grid_id);
		adapter=new  GridAdapter(numbers, this);
		gridView.setAdapter(adapter);

	}

}

 

Screenshot:

customgrid

Download

You can also download the above ListView Example here.

Related Posts:

GridView Array Adapter Example

ListView ArrayAdapter Example

Custom ListView Examle

Advertisements

Spinners in android example

Spinners provide a way to select one value from a set. The spinner displays a dropdown menu with all available values, from which the user can select a new one. In the default state, a spinner shows its currently selected value.

To add a list of values to the spinner, you then need to specify a SpinnerAdapter in your Activity, which extends Adapter class.. A spinner adapter allows to  define two different views: one that shows the data in the spinner itself and one that shows the data in the drop down list when the spinner is pressed.

Here is a complete example that shows the usage of spinner.

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:background="@drawable/bg_cyan"
android:gravity="center">

<Spinner
android:id="@+id/spinner_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</RelativeLayout>

MainActivity.java


import android.os.Bundle;

import android.app.Activity;

import android.util.Log;

import android.view.Menu;

import android.view.View;

import android.widget.AdapterView;

import android.widget.ArrayAdapter;

import android.widget.Spinner;

import android.widget.AdapterView.OnItemSelectedListener;

public class MainActivity extends Activity {

Spinner spin;

String spin_val;

String[] gender = { "Male", "Female" };//array of strings used to populate the spinner

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);//setting layout

spin = (Spinner) findViewById(R.id.spinner_id);//fetching view's id

//Register a callback to be invoked when an item in this AdapterView has been selected

spin.setOnItemSelectedListener(<b>new</b> OnItemSelectedListener() {

@Override

public void onItemSelected(AdapterView<?> arg0, View arg1,

int  position, long id) {

// TODO Auto-generated method stub

spin_val = gender[position];//saving the value selected

}

@Override

public void onNothingSelected(AdapterView<?> arg0) {

// TODO Auto-generated method stub

}

});

//setting array adaptors to spinners

//ArrayAdapter is a BaseAdapter that is backed by an array of arbitrary objects

ArrayAdapter<String> spin_adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, gender);

// setting adapters to spinners

spin.setAdapter(spin_adapter);

}

}

I’m also attaching my  spinner_Demo project for your reference. 🙂

Screenshots:

spin1spin3         spin2

PreferenceActivity in Android

PreferenceActivity -This is the base class for an activity to show a hierarchy of preferences to the user. It is usually  used to create a standard looking settings screen for any application.

The values are stored in SharedPreferences automatically by the PreferenceActivity.

The list of settings, are defined in xml file in xml folder  which is inside the res folder.

The given example explains its usage.

Firstly ,create a xml file in xml folder which is  inside the res folder.

settings.xml


<?xml vesion="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

<PreferenceCategory android:title="Application Settings" >
<Preference
android:dialogTitle="Picture"
android:key="picture"
android:summary="Select background picture"
android:title="Select background type" />
<Preference
android:dialogTitle="change password"
android:key="password"
android:summary="Change lock password"
android:title="change lock password" />

<CheckBoxPreference
android:defaultValue="true"
android:key="cb_vibrate"
android:summaryOff="Vibration Deactivated"
android:summaryOn="Vibration Activated"
android:title="Vibration Activation" />
<CheckBoxPreference
android:defaultValue="false"
android:key="cb_enable"
android:summaryOff="Locker Disabled"
android:summaryOn="Locker Enabled"
android:title="Enable "/>

<CheckBoxPreference
android:defaultValue="false"
android:key="cb_home"
android:summaryOff="Home Key Enabled"
android:summaryOn="Home Key Disabled"
android:title="Disable Home Key" />

</PreferenceCategory>
</PreferenceScreen>

The layout for the SettingActivity which uses a ListView and all the setting preferences will be displayed in the list view.  The same is given below.

setting_screen.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:orientation="vertical">

<ListView android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />

</RelativeLayout>

Now, this class extends PreferenceActivity implements OnPreferenceChangeListener.When ever the preference value is changed the OnPreferenceClickListener is used to do the required action.


public class SettingActivity extends PreferenceActivity implements

Preference.OnPreferenceChangeListener {

static ChartBoost cb;

String TAG = "chartboost";

Preferences preferences;

@SuppressWarnings("deprecation")

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.setting_screen);// list view

addPreferencesFromResource(R.xml.settings);// adding preferences

}

//fetching the required prefereence

final Preference prefimg = (Preference) findPreference("picture");

//setting PreferenceClickListener on the preference

prefimg.setOnPreferenceClickListener(new OnPreferenceClickListener() {

// if select background is selected

public boolean onPreferenceClick(Preference preference) {

//preference clicked

Intent i = new Intent(SettingActivity.this, GalleryView.class);                          startActivity(i);

// put your code here

return true;

}

Similarly , you can add action code whenever there is click on the preference setting.

Hence ,PrefrenceActivity  provides massive advantage over Prefrences as saving of preferences is automatic and hassle free.Here’s a screenshot of the example given above:

Screenshot:

PreferenceActivity Example

Related Posts:

Difference between sqlite and shared preferences in android

Using shared preferences in android

Zoomin animation on picture in android

Zoomin animation falls under the category of View Animation. The view animation framework animations, which can both be declared in XML.

The  zoomin animation xml file is given below :

Zoomin.xml


<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
 android:interpolator="@android:anim/decelerate_interpolator">
 <scale android:fromXScale="2.0" android:toXScale="1.0"
 android:fromYScale="2.0" android:toYScale="1.0"
 android:pivotX="50%p" android:pivotY="50%p"
 android:duration="@android:integer/config_longAnimTime" />
</set>
  • <set> contains other animation elements.
  • <scale > is a  resizing animation tag. You can specify the center point of the image from which it grows outward (or inward) by specifying pivotX and pivotY.
  • fromXScale/fromYScale represents the initial state and toXScale/toYScale represent the final state .

Hence , in this example the image is zoomed to its double size as “1.0” scale specifies no change.

Note: The zoomin.xml is created in anim folder which is a part of res folder.

The code for loading and starting the animation is given below.

 


public void onItemClick( View v)

{

Animation animLinear = AnimationUtils.loadAnimation(mContext, R.anim.zoomin);

v.startAnimation(animLinear);//starts the animation

}

android.view.animation.AnimationUtils  defines common utilities for working with animations and loadAnimation .loads an animation object from a resource anim folder.

Hence ,create the animation xml file first and then add the above code

Srcreenshots:

Screenshot1                   Screenshot 2                 Screenshot 3

translate animation in android example

Translate Animation controls the position and location of a layout or button or any view on which animation is being applied. It can move an object either in x direction or y direction.

Syntax :

TranslateAnimation transAnimation= new TranslateAnimation(fromXposition, toXPosition, fromYPosition, toYPosition);

  • fromXposition- x coordinate from  where animation should start
  • toXPosition- x coordinate at which animation would end
  • fromYPosition- y coordinate from where animation should start.
  • toYPosition- y coordinate at which animation would end.
  1. If we want to translate only in X direction then we set fromYPosition and toYPosition as zero.
  2. If we want to translate only in Y direction then we set fromXPosition and toXPosition as zero.

There is  another method in which we ,create an anim folder in the res folder. In this folder  we add our animation xml .We use a translate tag  in which we specify the attribute values.

In the below xml

android:duration defines the time of execution of animation

android:repeatCount specifies the no. of times the animation should be repeated ,

android:fromYDelta defines y coordinate from  where animation should start

android:toYDelta defines y coordinate at which animation would end.

line_translate.xml


<set  xmlns:android="http://schemas.android.com/apk/res/android">

<translate android:duration="300" android:repeatCount="1 android:fromYDelta="0.0" android:toYDelta="174.0" />

</set>

Code:


Animation lineTranslate;

//loading xml from anim folder

Animation localAnimation = AnimationUtils.loadAnimation(this, R.anim.line_translate);

//You can now apply the animation to a view

view.startAnimation(transAnimation);

Translate Animation can change the visual appearance of an object, but they cannot change the objects themselves. That is, if you apply a translate animation to a view, it would move to a new position but its click events would not get fired whereas the click events would still get fired at its previous position. This happens because the view is still at its original position. In order to overcome this, we can use ObjectAnimation which actually moves an object. Object Animation is the only animation which actually moves an object. You can create Translate animation using ObjectAnimator.


ObjectAnimator transAnimation= ObjectAnimator.ofFloat(view, propertyName, fromX, toX);

transAnimation.setDuration(3000);//set duration

transAnimation.start();//start animation

Here,

  • view  -this is the view on which animation is to be applied
  • propertyName-The property being animated.
  • FromX,toX-A set of values that the animation will animate between over time.

Why develop for android ?

Aside

Android is an open-source platform based on the Linux kernel , developed by the Open Handset Alliance, led by Google and is installed on thousands of devices from a wide range of manufacturers. Android operating system primarily is designed for mobile devices such as smartphones and tabs utilizing ARM processors. Android became the world’s leading smartphone platform at the end of 2010.

Android’s free development tools helps you to start app development at little or no cost. When your app is  ready , you can publish it to Google’s Android Market. Publishing to Android Market incurs a one-off registration fee, unlike Apple’s App Store which famously reviews each submission, makes your application available for customers to download and buy after a quick review process. There is a contrast in the way Apple has set up their development environment. Firstly, you need a Mac to develop on iOS.  Even if you do have a Mac, you can’t just download XCode (iOS’s SDK) ,you need to sign up for Apple’s Developer Program to get XCode, which comes at a hefty fee. This is  quite an investment if you just want to learn about the platform .With Android you can install an app to your phone from any source, not just the Android Market. But with iOS you can only install from the App Store unless you jailbreak your phone and this has a big impact on developers.

Some more advantages of android development are as follows :

  • The Android SDK is available for Windows, Mac and Linux, so you don’t need to pay for new hardware to start writing applications.
  • An SDK built on Java. If you’re familiar with the Java programming language, you’re already halfway there.
  • By distributing your application on Android Market, it’s available to large number of users world wide. Also, there are many app stores available where you can upload your apps..