Friday, October 14, 2016

Android Listview Multiple item type example

If you want to make a listview with different type of item for example to show a list of students with a label header based on their faculty follow these simple steps :


1.  Create a layout activity with name activity_listview.xml
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/listView"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</ListView>

2. Insert this png icon into drawable folder. name it ic_picture.png
3. Create item layout to represent a student, name it item_student.xml
 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:padding="16dp"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/imgStudent"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:scaleType="centerCrop"/>

    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1">

        <TextView
            android:id="@+id/textName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <TextView
            android:id="@+id/textID"
            android:layout_below="@+id/textName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </RelativeLayout>

</LinearLayout>

4. Create item header layout, name it item_header.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimary"
    android:padding="12dp">
    <TextView
        android:id="@+id/textHeader"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textSize="16sp"
        android:textStyle="bold"
        android:textColor="#ffffff"
        android:gravity="center"/>

</RelativeLayout>
5. Create BaseItem.java class
package com.example.myapplication.customarray;

/**
 * Created by SONY on 15/10/2016.
 */
public class BaseItem {
    
    public int type;
}


6. Create StudentItem.java class that extends BaseItem.java
package com.example.myapplication.customarray;

/**
 * Created by SONY on 14/10/2016.
 */
public class StudentItem extends BaseItem {
    public String name;
    public String id;
    public int picture;

}
7. Create HeaderItem.java class that extends BaseItem.java
package com.example.myapplication.customarray;

/**
 * Created by SONY on 15/10/2016.
 */
public class HeaderItem extends BaseItem {

    public String label;
}

8. Create CustomAdapter.java class
package com.example.myapplication.customarray;

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

import com.example.myapplication.R;
import java.util.List;

/**
 * Created by SONY on 14/10/2016.
 */
public class CustomAdapter extends ArrayAdapter<BaseItem> {

    private List<BaseItem> data;

    public CustomAdapter(Context context, List<BaseItem> data) {
        super(context, 0, data);
        this.data = data;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        BaseItem baseItem = data.get(position);
        if(convertView == null) {
            if(baseItem.type == 0) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_student, parent, false);
                convertView.setTag(ViewHolder.createHolder(convertView));
            }
            else {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_header, parent, false);
                convertView.setTag(ViewHolderHeader.createViewHolder(convertView));
            }
        }
        if(baseItem.type == 0) {
            ViewHolder holder = (ViewHolder) convertView.getTag();
            StudentItem student = (StudentItem) data.get(position);
            holder.textName.setText(student.name);
            holder.textID.setText(student.id);
            holder.imgStudent.setImageResource(student.picture);
        }
        else {
            ViewHolderHeader holderHeader = (ViewHolderHeader) convertView.getTag();
            HeaderItem headerItem = (HeaderItem) data.get(position);
            holderHeader.textLabel.setText(headerItem.label);
        }
       return convertView;
    }

    @Override
    public int getCount( ) {
        return data.size();
    }
    @Override
    public int getViewTypeCount() {
        return 2;
    }
    @Override
    public int getItemViewType(int position) {
        BaseItem item = data.get(position);
        return item.type;
    }



    public static class ViewHolder  {
        public TextView textName;
        public TextView textID;
        public ImageView imgStudent;

        public static final ViewHolder createHolder(View view) {
            ViewHolder holder = new ViewHolder();
            holder.textName = (TextView) view.findViewById(R.id.textName);
            holder.textID = (TextView) view.findViewById(R.id.textID);
            holder.imgStudent = (ImageView) view.findViewById(R.id.imgStudent);
            return holder;
        }
    }
    public static class ViewHolderHeader {
        public TextView textLabel;

        public static final ViewHolderHeader createViewHolder(View view) {
            ViewHolderHeader holderHeader = new ViewHolderHeader();
            holderHeader.textLabel = (TextView)view.findViewById(R.id.textHeader);
            return holderHeader;
        }
    }
}

9. Create CustomActivity.java class
package com.example.myapplication.customarray;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import com.example.myapplication.R;
import java.util.ArrayList;


/**
 * Created by SONY on 14/10/2016.
 */
public class CustomActivity extends Activity {
    private ListView listView;
    private CustomAdapter adapter;
    private ArrayList<BaseItem> data = new ArrayList<BaseItem>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_listview);
        listView = (ListView) findViewById(R.id.listView);
        adapter = new CustomAdapter(this, data);
        listView.setAdapter(adapter);
        populateListView();
    }

    private void populateListView() {
        HeaderItem headerItem1 = new HeaderItem();
        headerItem1.type = 1;
        headerItem1.label = "Engineering";

        StudentItem student1 = new StudentItem();
        student1.type = 0;
        student1.name = "Muhammad";
        student1.id = "123455";
        student1.picture = R.drawable.ic_picture;

        StudentItem student2 = new StudentItem();
        student2.type = 0;
        student2.name = "Ali";
        student2.id = "123456";
        student2.picture = R.drawable.ic_picture;

        StudentItem student3 = new StudentItem();
        student3.type = 0;
        student3.name = "Rahman";
        student3.id = "123457";
        student3.picture = R.drawable.ic_picture;

        HeaderItem headerItem2 = new HeaderItem();
        headerItem2.type = 1;
        headerItem2.label = "Medicine";

        StudentItem student4 = new StudentItem();
        student4.type = 0;
        student4.name = "David";
        student4.id = "123458";
        student4.picture = R.drawable.ic_picture;

        StudentItem student5 = new StudentItem();
        student5.type = 0;
        student5.name = "Roberts";
        student5.id = "123459";
        student5.picture = R.drawable.ic_picture;

        StudentItem student6 = new StudentItem();
        student6.type = 0;
        student6.name = "Ismail";
        student6.id = "123451";
        student6.picture = R.drawable.ic_picture;
        data.add(headerItem1);
        data.add(student1);
        data.add(student2);
        data.add(student3);
        data.add(headerItem2);
        data.add(student4);
        data.add(student5);
        data.add(student6);
        adapter.notifyDataSetChanged();

    }
}

10. Create AndroidManifest.xml file. Warning: adjust your activity package name in line <activity android:name=<your_activity_package>>. If your package name is not correct the app will crash at run time.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapplication">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".customarray.CustomActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>
11. After you run your application you should see the screen like this. notice label item is shown now (Engineering and Medicine).
Thank you for visiting our website. Just comment below if you have any question to ask.

No comments:

Post a Comment