Android Interview Questions - SPLessons

Android GridView

Chapter 7

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Android GridView

Android GridView

Android GridView allows you to display items in a two-dimensional, scrollable grid. The grid items are automatically inserted to the layout using a ListAdapter. Android GridView layout is mainly used to build applications like image viewer, and audio player, in which elements should be represented in grid format. 

An adapter acts as a bridge between UI components and the data source and fills data into UI Component. Perhaps, it can be used to provide data to various layouts such as spinner, list view and grid view.

Both ListView and GridView are subclasses of AdapterView. Adapter is used to retrieve data from an external source and creates a view that represents each entry. In this tutorial, we will explain you how to display the components in GridView using custom Adapter.

GridView can be used in 2 ways:

Create MainActivity.java under src/<your packagename> of your project and save 4 images mango, orange, banana and watermelon in res/drawable folder.

MainActivity.java:

public class MainActivity extends Activity {

    Context context;

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

        Button access=(Button)findViewById(R.id.button1);

        final GridView list=(GridView)findViewById(R.id.gridView1);

        context=this;

        final ArrayList<String> aList=new ArrayList<String>();
        aList.add("Mango");
        aList.add("Orange");
        aList.add("Banana");
        aList.add("Watermelon");

        final Integer[] array={R.drawable.mango,R.drawable.orange,R.drawable.banana,R.drawable.watermelon};

        //on click access
        access.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
            //custom adapter
                list.setAdapter(new Image(MainActivity.this,aList,array));
               /*default adapter
                 ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                 android.R.layout.simple_list_item_1, aList);
                 gridView.setAdapter(adapter);*/
            }
        });
        //on click gridview(default adapter)
        /*list.setOnItemClickListener(new OnItemClickListener() {
          public void onItemClick(AdapterView<?> parent, View v,nt position, long id) {
          Toast.makeText(getApplicationContext(),“You clicked at Index”+position, Toast.LENGTH_SHORT).show();

         }
          });*/

    }

}

Create activity_main.xml in res/layout folder.

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    android:background="#300890"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:background="#009ACD"
        android:layout_gravity="center"
        android:gravity="center"
        android:text="Access grid" />

    <GridView
        android:id="@+id/gridView1"
        android:scrollbars="none"
        android:layout_marginTop="10dp"
        android:columnWidth="100dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:verticalSpacing="10dp"
        android:horizontalSpacing="10dp"
        android:stretchMode="columnWidth"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_gravity="center"
        android:gravity="center"
        android:cacheColorHint="#00000000"
        android:numColumns="2" >
    </GridView>

</LinearLayout>

Create Image.java adapter class under src folder.

Image.java:

public class Image extends BaseAdapter {
    private Context mContext;
    ArrayList<String> aList;
    ViewHolder holder;
    Integer[] array;

    public Image(Context mContext, ArrayList<String> aList,
                 Integer[] array) {
// TODO Auto-generated constructor stub
        this.mContext = mContext;
        this.aList=aList;
        this.array=array;
    }

    @Override
    public int getCount() {
        return aList.size();
    }

    @Override
    public Object getItem(int position) {
        return aList.get(position);
    }

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

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

        if(convertView==null)
        {
            LayoutInflater inflater=(LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView=inflater.inflate(R.layout.activity_image, null);
            holder=new ViewHolder();

            holder.imageView=(ImageView)convertView.findViewById(R.id.imageViewFruit);

            holder.title=(TextView)convertView.findViewById(R.id.textViewTitle);

            convertView.setTag(holder);
        }
        else
        {
            holder=(ViewHolder) convertView.getTag();
        }

        holder.imageView.setImageResource(array[position]);
        holder.title.setText(aList.get(position));
        holder. imageView. setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Toast.makeText(mContext,"You clicked at Index"+position,Toast.LENGTH_LONG).show();

            }
        });

        return convertView;
    }
    public class ViewHolder{

        ImageView imageView;
        TextView title;

    }
}

Create activity_image.xml in res/layout folder.

activity_image.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageViewFruit"
        android:layout_width="100dp"
        android:layout_height="80dp"
        android:paddingLeft="2dp"
        android:paddingRight="2dp"
        android:paddingBottom="1dp"
        android:paddingTop="2dp"
        android:scaleType="fitXY"

        />
    <LinearLayout
        android:layout_width="100dp"
        android:layout_height="wrap_content"

        android:orientation="vertical" >
        <TextView
            android:id="@+id/textViewTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:maxLines="1"
            android:minLines="1"
            android:paddingRight="5dp"
            android:paddingLeft="10dp"
            android:textColor="#FFFFFF"
            android:textSize="12sp"
            android:text="Fruit Name" />

    </LinearLayout>

</LinearLayout>

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.spl.myproject"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.spl.myproject.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Output: