Android Custom ListFragment Using BaseAdapter

By | May 25, 2014

In the Previous Tutorial we have see an example of Simple List Fragment using ArrayAdpter , here in this tutorial we will see how to create a custom listfragment using basedapter,and in this example we will try to customize items of listfragment with ImageView and TextView .

Project Detail

Project Name CustomListFragment
Package com.pavan.customlistfragment
Minimum SDK API 8
Target SDK API 17
Theme Holo Light with Dark Action Bar

String Constant

Before i start coding i will initialize of the string constants inside string.xml file under res/values directory. and also I have edited the images and added to the drawable resource directory which you can find inside the download source code.

file: strings.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<resources>

    <string name=”app_name“>CustomListFragment</string>
    <string name=”action_settings“>Settings</string>
    <string name=”hello_world“>Hello world!</string>
    <string name=”imgdesc“>imgdesc</string>

    <string-array name=”titles>
        <item>Home</item>
        <item>Tutorials</item>
        <item>My Apps</item>
        <item>OS Versions</item>
        <item>Tools</item>
        <item>About Us</item>
    </string-array>

    <array name=”icons“>
        <item>@drawable/home</item>
        <item>@drawable/tutorials</item>
        <item>@drawable/app</item>
        <item>@drawable/os</item>
        <item>@drawable/tool</item>
        <item>@drawable/about</item>
    </array>

</resources>

XML Layout

After Initializing String constants , next step is creating xml layout so i will create two xml files inside res/layout.

  1.  activity_main.xml.
  2.  list_fragment.xml.
  3.  list_item.xml.

1. activity_main.xml :- Inside activity_main.xml file we have LinearLayout tag as parent view and fragment tag as a child view , and for this fragment tag we will be inflating it with list_fragment.xml .

file: 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:orientation=”vertical” >

    <fragment
        android:id=”@+id/fragment1″
        android:name=”com.pavan.customlistfragment.MyListFragment”
        android:layout_width=”match_parent”
        android:layout_height=”match_parent” />

</LinearLayout>

2. list_fragment.xml :-

  1. Inside the list_fragment.xml file we have LinearLayout tag as parent view , and ListView and TextView act as childview to it .
  2. Here listview and textview takes a special kind of id’s @android:id/list and @android:id/empty.
  3. The purpose of  TextView is used to show some text message when listview is empty .

file: list_fragment.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” >

    <ListView
        android:id=”@android:id/list”
        android:layout_width=”match_parent”
        android:layout_height=”wrap_content” >
    </ListView>

    <TextView
        android:id=”@android:id/empty”
        android:layout_width=”match_parent”
        android:layout_height=”wrap_content” >
    </TextView>

</LinearLayout>

3. list_item.xml : – This xml layout is used customize items of listfragment , this xml layout contains RelativeLayout as parentview to which ImageView and Textview we added as childView .

file:list_item.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=”48dp”
    android:padding=”5dp” >

    <ImageView
        android:id=”@+id/icon”
        android:layout_width=”50dp”
        android:layout_height=”wrap_content”
        android:layout_alignParentLeft=”true”
        android:layout_centerVertical=”true”
        android:layout_marginLeft=”12dp”
        android:layout_marginRight=”12dp”
        android:contentDescription=”@string/imgdesc” />

    <TextView
        android:id=”@+id/title”
        android:layout_width=”wrap_content”
        android:layout_height=”match_parent”
        android:layout_marginTop=”10dp”
        android:layout_toRightOf=”@id/icon”
        android:gravity=”center_vertical”
        android:textColor=”#000000″
        android:textSize=”20sp” />

</RelativeLayout>

Custom Adapter

Java Beans

Create a Bean Class RowItem which is used for setting and getting row data of each items in listfragment    ( imageview and TextView ).

file: RowItem.java

package com.pavan.customlistfragment;

public class RowItem {

    private String title;
    private int icon;

    public RowItem(String title, int icon) {
        this.title = title;
        this.icon = icon;

    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public int getIcon() {
        return icon;
    }

    public void setIcon(int icon) {
        this.icon = icon;
    }

}

Custom Adapter 

Create a Custom adapter which extends BaseAdapter , this is used for inflating each row items of the listfragment with list_item.xml layout inside getView method.

file:CustomAdapter.java

package com.pavan.customlistfragment;

import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CustomAdapter extends BaseAdapter {

    Context context;
    List<RowItem> rowItem;

    CustomAdapter(Context context, List<RowItem> rowItem) {
        this.context = context;
        this.rowItem = rowItem;

    }

    @Override
    public int getCount() {

        return rowItem.size();
    }

    @Override
    public Object getItem(int position) {

        return rowItem.get(position);
    }

    @Override
    public long getItemId(int position) {

        return rowItem.indexOf(getItem(position));
    }

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

        if (convertView == null) {
            LayoutInflater mInflater = (LayoutInflater) context
                    .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
            convertView = mInflater.inflate(R.layout.list_item, null);
        }

        ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);
        TextView txtTitle = (TextView) convertView.findViewById(R.id.title);

        RowItem row_pos = rowItem.get(position);
        // setting the image resource and title
        imgIcon.setImageResource(row_pos.getIcon());
        txtTitle.setText(row_pos.getTitle());

        return convertView;

    }

}

ListFragment

  1. Create a class MyListFragment and extend it to ListFragment .
  2.  Inside the onCreateView() method , inflate the view with above defined list_fragment xml layout .
  3. Inside the onActivityCreated() method  , set the listfragment with above defined custom adapter and also set the onItemClickListener .
  4. Inside the OnItemClickListener() method , display a toast message with Item name which is being clicked .

file:MyListFragment.java

package com.pavan.customlistfragment;

import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.ListFragment;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MyListFragment extends ListFragment implements OnItemClickListener {

    String[] menutitles;
    TypedArray menuIcons;

    CustomAdapter adapter;
    private List<RowItem> rowItems;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        return inflater.inflate(R.layout.list_fragment, null, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {

        super.onActivityCreated(savedInstanceState);

        menutitles = getResources().getStringArray(R.array.titles);
        menuIcons = getResources().obtainTypedArray(R.array.icons);

        rowItems = new ArrayList<RowItem>();

        for (int i = 0; i < menutitles.length; i++) {
            RowItem items = new RowItem(menutitles[i], menuIcons.getResourceId(
                    i, -1));

            rowItems.add(items);
        }

        adapter = new CustomAdapter(getActivity(), rowItems);
        setListAdapter(adapter);
        getListView().setOnItemClickListener(this);

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {

        Toast.makeText(getActivity(), menutitles[position], Toast.LENGTH_SHORT)
                .show();

    }

}

 Main Activity

Finally Inside the MainActivity.java inside the onCreate() , method set the content of the view with above defined activity_main.xml file .

file:MainActivity.java

package com.pavan.customlistfragment;

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

public class MainActivity extends Activity {

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

}

  • Your site fail to download the source code. I processed my subscription but when I try to download say "no recognized email". So shity!

  • @juan
    I frequently update the database manually it takes time for me , i update every 10 hours ,sorry you tried to download when it is not updated

    now you can download all the resource of this blog

    Sorry

  • Thanks u saved ma time…… 🙂

  • Finally found the holy grail!! Thanks so much!!!

  • Hey Bro.
    U said you update database every 10 hours.
    It is still not recognize me as a subscribe user.
    Please update quick.
    I am waiting since yesterday.

  • @Soe Chit
    It's Updated , Sorry some server issue now it's fixed hope you can download

  • Why doesnt the onItemClick work in my code using the same code?

  • J

    Thank you this helped me out a bunch 🙂

  • I have Navigation drawer with 2 fragments. Fragment1. Diasplay Event data with dates (retrieved data from database)
    Fragment2. setting alarm for events for that i need to send event date from Fragment 1 to fragment 2 without any onClickmethd…. is it possible to send data from one fragment to anoter fragment in Navigation drawer..?

  • i was getting error on R.array.title
    R.array.icon

  • HOW TO LOAD CUSTOM LISTVIEW WITH IMAGEVIEW AND TEXTVIEW DYNAMICALLY USING FRAGMENT

  • please i get error in this two lines, it like the methods are missing and i don't know where to put them
    setListAdapter(adapter);
    getListView().setOnItemClickListener(this);

  • thanks lot