Android GridView And ImageSwitcher Example

android.widget.GridView is used to display multiple view components on the screen by row and column distribution. It is a subclass of AbsListViewGridView also needs Adapter to provide display data, including SimpleAdapter or BaseAdapter, and the usage is very similar to ListView.

android.widget.ImageSwitcher is derived from FrameLayout, it is used to display images also. It is similar to ImageView, but the difference is that ImageSwitcher can add animation effect when the image is switched.

1. GridView Properties And Methods.

  1. android:numColumns : The columns number of GridView.
  2. android:horizontalSpacing : The horizontal space between each Grid item.
  3. android:verticalSpacing : The vertical space between each Grid item.
  4. android:stretchMode : none — Do not stretch. columnWidth — Only stretch grid view column. spacingWidth — Only stretch grid view space. spacingWidthUniform — Stretch both grid view column and space.
  5. setOnItemClickListener() : Set a listener listen to grid view item click event.
  6. setOnItemSelectedListener() : Set a listener listen to grid view item select event.

2. ImageSwitcher Usage Steps.

  1. Get the ImageSwitcher instance via findViewById() method.
  2. Call ImageSwitcher‘s setFactory() method to set a ImageSwitcher.ViewFactory instance to it.
  3. The ViewFactory instance should override it’s makeView() method. The makeView() method will return an ImageView object.

3. Android GridView And ImageSwitcher Example.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/CCJwzvcsqGg

activity_grid_view.xml

This is the activity layout xml file saved in app / res / layout folder.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <GridView
        android:id="@+id/imageGridView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:verticalSpacing="5pt"
        android:horizontalSpacing="5pt"
        android:numColumns="3"
        android:stretchMode="columnWidth"/>

    <ImageSwitcher
        android:id="@+id/gridImageSwitcher"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

GridViewActivity.java

package com.dev2qa.example;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.ViewSwitcher;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GridViewActivity extends AppCompatActivity {

    // Image drawable resource id array.
    private int[] imageDrawableIdArr = {R.drawable.light_turn_on, R.drawable.light_turn_on, R.drawable.light_turn_on, R.drawable.light_turn_off, R.drawable.light_turn_off, R.drawable.light_turn_off};

    // Store grid item.
    private List<Map<String, Object>> gridItemList = null;

    // The key name of grid item map.
    private String GRID_ITEM_MAP_KEY_NAME = "image";

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

        setTitle("dev2qa.com --- Android GridView Example");

        // Get ImageSwitcher and set it's animation effect.
        final ImageSwitcher imageSwitcher = (ImageSwitcher)findViewById(R.id.gridImageSwitcher);
        imageSwitcher.setInAnimation(this, android.R.anim.fade_in);
        imageSwitcher.setOutAnimation(this, android.R.anim.fade_out);

        // Set ImageSwitcher ViewFactory, this factory will return the ImageView object which will be displayed.
        imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
            @Override
            public View makeView() {
                ImageView imgView = new ImageView(GridViewActivity.this);
                imgView.setScaleType(ImageView.ScaleType.FIT_CENTER);
                imgView.setBackgroundColor(Color.GREEN);
                ImageSwitcher.LayoutParams imgLayoutParams = new ImageSwitcher.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL);
                imgView.setLayoutParams(imgLayoutParams);
                return imgView;
            }
        });

        // Initialize grid view item display image drawable id data list.
        this.initGridViewItemData();

        // Create a SimpleAdapter.
        SimpleAdapter simpleAdapter = new SimpleAdapter(this, this.gridItemList, R.layout.activity_grid_view_cell ,new String[]{this.GRID_ITEM_MAP_KEY_NAME}, new int[]{R.id.gridCellImageView});

        // Get GridView and set data adapter.
        GridView gridView = (GridView)findViewById(R.id.imageGridView);
        gridView.setAdapter(simpleAdapter);

        // Response to grid item selected event.
        gridView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int gridIndex, long id) {
                int selectImageDrawableId = imageDrawableIdArr[gridIndex];
                imageSwitcher.setImageResource(selectImageDrawableId);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        // Response to grid item click event.
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int gridIndex, long id) {
                int selectImageDrawableId = imageDrawableIdArr[gridIndex];
                imageSwitcher.setImageResource(selectImageDrawableId);
            }
        });
    }

    // This method will initialize the grid view data.
    private void initGridViewItemData()
    {
        if(this.gridItemList==null)
        {
            this.gridItemList = new ArrayList<Map<String, Object>>();
        }

        int imageCount = this.imageDrawableIdArr.length;
        for(int i = 0; i< imageCount ; i++)
        {
            int imageDrawableId = this.imageDrawableIdArr[i];
            Map<String, Object> gridItemMap = new HashMap<String, Object>();
            gridItemMap.put(this.GRID_ITEM_MAP_KEY_NAME, imageDrawableId);

            this.gridItemList.add(gridItemMap);
        }
    }

}

activity_grid_view_cell.xml

This is the grid cell layout xml file. It is used for SimpleAdapter to display one GridView item. It is saved in app / res / layout directory also.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/gridCellImageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.