Saturday, October 17, 2015

Android Custom Adapter for Grid View

The aim was to display a grid icon and the label corresponding to it, just like below screenshot

This can be done by giving a layout for each cell and this layout view is returned as a layout defined in this file

A sample layout for this is

"1.0" encoding="utf-8"?
android:id="@+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="5dp"

android:layout_height="64dp"
android:id="@+id/imageView1"
android:layout_width="64dp"
android:src="@drawable/ic_launcher"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"

android:text="TextView"
android:layout_height="wrap_content"
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_below="@+id/imageView1"
android:layout_marginTop="2dp"
android:layout_centerHorizontal="true"
android:textSize="18sp"
android:ellipsize="marquee"



In the getView Method of the Adapter class, below will be the code 

public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    ViewHolder view;
    LayoutInflater inflator = activity.getLayoutInflater();
    
    if(convertView==null)
    {
        view = new ViewHolder();
        convertView = inflator.inflate(R.layout.gridview_row, null);
        
        view.txtViewTitle = (TextView) convertView.findViewById(R.id.textView1);
        view.imgViewFlag = (ImageView) convertView.findViewById(R.id.imageView1);
        
        convertView.setTag(view);
    }
    else
    {
        view = (ViewHolder) convertView.getTag();
    }
    
    view.txtViewTitle.setText(listCountry.get(position));
    if(itemStates[position] == 0) {
        view.imgViewFlag.setImageResource(listFlagOff.get(position));
    }
    else
    {
        view.imgViewFlag.setImageResource(listFlag.get(position));
    }
    return convertView;
}
}

It is convenient to have tag as object for each view. This way we can associate arbitrary object. Where as in iOS, the tag has to be always int. 


References:

No comments:

Post a Comment