Android Checkbox and Textview in ListView Tutorial

In this post, I will tell you how to use checkbox in Listview. In Earlier posts, I had explained how to use ListView.

So, Let’s Start

1.To create Listview we need the following:-

a.Model class whose object we store in ArrayList that we pass to adapter.

b.Adapter class to be set to Listview.

c.layout for adapter class.

d.Activity class containing Listview.

e.layout for activity class.

Model class

MyItem.java

package com.androidruler.customlistview;

/**
 * Created by apple on 21/02/16.
 */
public class MyItem {

    private String title="";
    private boolean checked=false;

    public MyItem(String title,boolean checked)
    {
        this.title=title;
        this.checked=checked;
    }

    public boolean isChecked() {
        return checked;
    }

    public void setChecked(boolean checked) {
        this.checked = checked;
    }

    public String getTitle() {
        return title;
    }

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

layout for adapter class

myadapter.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:layout_height="match_parent">
    <TextView
        android:id="@+id/adaptertextview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <CheckBox
        android:id="@+id/adaptercheckbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

adapter class

MyCustomAdapter.java

package com.androidruler.customlistview;

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.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by coderzpassion on 13/03/16.
 */
public class MyCustomAdapter extends BaseAdapter {

    private Context mContext;
    ArrayList<MyItem> mylist=new ArrayList<>();


    public MyCustomAdapter(ArrayList<MyItem> itemArray,Context mContext) {
        super();
        this.mContext = mContext;
      mylist=itemArray;
    }

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

    }

    @Override
    public String getItem(int position) {
        return mylist.get(position).toString();
    }

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

    public void onItemSelected(int position) {

    }

    public class ViewHolder {
        public TextView nametext;
        public CheckBox tick;

    }

    @Override
    public View getView(final int position, View convertView,
                        ViewGroup parent) {
        // TODO Auto-generated method stub
        ViewHolder view = null;
        LayoutInflater inflator = ((Activity) mContext).getLayoutInflater();

        if (view == null) {
            view = new ViewHolder();
            convertView = inflator.inflate(	R.layout.myadapter, null);

            view.nametext = (TextView) convertView.findViewById(R.id.adaptertextview);
            view.tick=(CheckBox)convertView.findViewById(R.id.adaptercheckbox);
            view.tick.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView,
                                             boolean isChecked) {
                    int getPosition = (Integer) buttonView.getTag(); // Here
                    // we get  the position that we have set for the checkbox using setTag.
                    mylist.get(getPosition).setChecked(buttonView.isChecked()); // Set the value of checkbox to maintain its state.

                    if (isChecked) {
                       //do sometheing here
                    }
                    else
                    {
                        // code here
                    }
                }
            });

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

        view.tick.setTag(position);
        view.nametext.setText("" + mylist.get(position).getTitle());
        view.tick.setChecked(mylist.get(position).isChecked());

        return convertView;
    }

}

layout for Activity class

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <ListView
        android:id="@+id/mainactivitylistview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:divider="@android:color/black"
        android:dividerHeight="2dp"
        android:descendantFocusability="afterDescendants"></ListView>

</RelativeLayout>

Activity class

MainActivity.java

package com.androidruler.customlistview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ListView mainactivity;
    // creating arraylist of MyItem type to set to adapter
    ArrayList<MyItem> myitems=new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mainactivity=(ListView)findViewById(R.id.mainactivitylistview);
          //Adding data i.e images and title to be set to adapter to populate listview
         //here i am passing  string to be set as title and boolean as a parameter to MyItem Constructor as our
        //ArrayList is type of MyItem
        myitems.add(new MyItem("First item",true));
        myitems.add(new MyItem("second item",false));
        myitems.add(new MyItem("third item",true));
        myitems.add(new MyItem("fourth item",false));
        myitems.add(new MyItem("fifth item",true));
        myitems.add(new MyItem("sixth item",false));
        myitems.add(new MyItem("seven item",true));
        myitems.add(new MyItem("First item",true));
        myitems.add(new MyItem("second item",false));
        myitems.add(new MyItem("third item",true));
        myitems.add(new MyItem("fourth item",false));
        myitems.add(new MyItem("fifth item",true));
        myitems.add(new MyItem("sixth item",false));
        myitems.add(new MyItem("seven item",true));
        myitems.add(new MyItem("First item",true));
        myitems.add(new MyItem("second item",false));
        myitems.add(new MyItem("third item",true));
        myitems.add(new MyItem("fourth item",false));
        myitems.add(new MyItem("fifth item",true));
        myitems.add(new MyItem("sixth item",false));
        myitems.add(new MyItem("seven item",true));


        //Creating Adapter object for setting to list
        MyCustomAdapter adapter=new MyCustomAdapter(myitems,MainActivity.this);
        mainactivity.setAdapter(adapter);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        //getMenuInflater().inflate(R.menu.menu_main, menu);  //this shows three dots at right corner on click settings open
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Output

workingwithcheckboxinlistview

Android ListView With Search Functionality(Data Filtering) Tutorial/Example

ListView With Search Functionality helps the user to easily get the results required.In search Functionality, we filter the data according to data entered by the user and thus showing the results user wants.So, Let’s Start to implement search functionality

  1. Open Eclipse or Android Studio -> New Project->Android Application Project-> Name of Application-> Follow all instructions and complete by clicking on Finish.
  2. We will need two layouts for this one for main screen containing view for search and second to show the results as required by the user.

//layout for main screen

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <EditText
        android:id="@+id/searchdata"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="enter to search"/>

    <ListView
        android:id="@+id/showdata"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"></ListView>

</LinearLayout>

//layout to show the results

searchresults.xml

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

    <TextView
        android:id="@+id/results"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:textSize="20dp"/>

</LinearLayout>

3. Now defining MainActivity.java, containg list and search editext  and adapter to set to list.

MainActivity.java

package com.coderzpassion.mylistviewsearch;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    //declaring variables
    private ListView listviewforresults;
    //Adapter for listview
    ArrayAdapter<String> adapter;
    //Edittext for search
    EditText searchdata;

    //ArrayList for listview
    ArrayList<String>  data=new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //intializing
        listviewforresults=(ListView)findViewById(R.id.showdata);
        searchdata=(EditText)findViewById(R.id.searchdata);

        //prepare dummy data for searching
        prepareDummyData();

        //set data to Adapter
        adapter=new ArrayAdapter<String>(MainActivity.this,R.layout.searchresults,R.id.results,data);
        listviewforresults.setAdapter(adapter);
        //search data when text changes in edittext
        searchdata.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                MainActivity.this.adapter.getFilter().filter(s);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    public void prepareDummyData()
    {
        data.add("India");
        data.add("Usa");
        data.add("Canada");
        data.add("Iran");
        data.add("Iraq");
        data.add("Russia");
        data.add("Uk");
        data.add("Cameroon");

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.coderzpassion.mylistviewsearch" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".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>

 

 

 

Android Expandable ListView Tutorial/Example

ExpandableListView allows the user to expand grouped set of items.Items are like ListView which are expanded when user click them.

Expandable ListView is used to categorize the data and a better to represent grouped data.

So Start building your Expandable Listview Sample.

1.Open Eclipse or Android Studio -> New Project->Android Application Project-> Name of Application-> Follow all instructions and complete by clicking on Finish.

2.For creating Expandable ListView we need three layouts one for the main screen contain expandable listview, second for headers which will be expanded and third for header’s items which be shown on header’s expansion.

//layout for mainactivity

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent"
    android:layout_height="match_parent"                 android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<ExpandableListView
    android:id="@+id/expandlist"
    android:layout_width="match_parent"
    android:layout_height="match_parent"></ExpandableListView>

</LinearLayout>

//layout for headers which will expand or collapse

listview_header.xml

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

    <TextView
        android:id="@+id/expandheader"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="25dp"
        android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
        android:textColor="@android:color/black"/>
</LinearLayout>

// layout for header’s items which will be visible on click of header’s

headers_items.xml

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

    <TextView
        android:id="@+id/headeritem"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="20dp"
        android:padding="5dp"/>
</LinearLayout>

3.Create Custom Adapter class by extending your adapter class to BaseExpandableListAdapter  like as follows

MyExpandableAdapter.java

package com.coderzpassion.expanlistsample;

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

import java.util.HashMap;
import java.util.List;


public class MyExpandableAdapter  extends BaseExpandableListAdapter{
    private Context con;
    private List<String> headers;
    private HashMap<String,List<String>> headeritems;

    public MyExpandableAdapter(Context context,List<String> listheaders,HashMap<String,List<String>> headerchilds)
    {
        this.con=context;
        this.headers=listheaders;
        this.headeritems=headerchilds;
    }

      // get child of header
    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return this.headeritems.get(this.headers.get(groupPosition)).get(childPosition);
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    // return the view of child

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        final String childname=(String)getChild(groupPosition,childPosition);
        if(convertView==null)
        {
            LayoutInflater inflater=(LayoutInflater)LayoutInflater.from(con);
            convertView=inflater.inflate(R.layout.header_items,null);
        }
        TextView listchild=(TextView)convertView.findViewById(R.id.headeritem);
        listchild.setText(childname);
        return convertView;
    }

     // returns children count of header
    @Override
    public int getChildrenCount(int groupPosition) {
        return this.headeritems.get(headers.get(groupPosition)).size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return this.headers.get(groupPosition);
    }

    @Override
    public int getGroupCount() {
        return this.headers.size();
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }
     
      //returns the view of group
    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        String headername=(String)getGroup(groupPosition);
        if(convertView==null)
        {
            LayoutInflater inflater=LayoutInflater.from(con);
            convertView=inflater.inflate(R.layout.listview_header,null);
        }
        TextView header=(TextView)convertView.findViewById(R.id.expandheader);
        header.setText(headername);
        return convertView;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }
}

4. After defining with Custom Expandable Listview Adapter now we will create the MainActivity class which contains ExpandableListview

MainActivity.java

package com.coderzpassion.expanlistsample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.Toast;

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

public class MainActivity extends AppCompatActivity {

    // declare the variable needed in activity
    MyExpandableAdapter expandableadapter;
    ExpandableListView expandableListView;
    List<String> headers;
    HashMap<String,List<String>> headeritems;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //get expandable listview
        expandableListView=(ExpandableListView)findViewById(R.id.expandlist);

        //get data to be set to list
        prepareDummyData();

        // get expandable list adapter
        expandableadapter=new MyExpandableAdapter(this,headers,headeritems);

        //set list adapter to list
        expandableListView.setAdapter(expandableadapter);

        //handling the header items click
        expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                Toast.makeText(MainActivity.this,headers.get(groupPosition)+"--"+headeritems.get(headers.get(groupPosition)).get(childPosition),Toast.LENGTH_SHORT).show();
                return false;
            }
        });

        //get the expand of headers
        expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
            @Override
            public void onGroupExpand(int groupPosition) {
                Toast.makeText(MainActivity.this,headers.get(groupPosition),Toast.LENGTH_SHORT).show();
            }
        });

        //get the collapse of headers
        expandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
            @Override
            public void onGroupCollapse(int groupPosition) {
                Toast.makeText(MainActivity.this,headers.get(groupPosition),Toast.LENGTH_SHORT).show();
            }
        });
    }
     // get dummy data to be set to adapter
    public void prepareDummyData()
    {
        headers=new ArrayList<String>();
        headeritems=new HashMap<String,List<String>>();
        //adding headers
        headers.add("Primary");
        headers.add("Senior Secondary");
        headers.add("College");

        //preparing header items data
        List<String> primary=new ArrayList<String>();
        primary.add("first class");
        primary.add("second class");
        primary.add("third class");

        List<String> secondary=new ArrayList<String>();
        secondary.add("eighth class");
        secondary.add("ninth class");
        secondary.add("tenth class");

        List<String> college=new ArrayList<String>();
        college.add("CSE");
        college.add("ECE");
        college.add("IT");
        //contain header and header items
        headeritems.put(headers.get(0), primary);
        headeritems.put(headers.get(1), secondary);
        headeritems.put(headers.get(2),college);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

 

Android Listview Example/Tutorial

To create Listview we need the following:-

  1. MainActivity class containing  Listview and will be the main screen.

MainActivity.java

package com.androidruler.simplelistview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ListView mainactivity;
    // creating arraylist of MyItem type to set to adapter
    ArrayList<String> myitems=new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mainactivity=(ListView)findViewById(R.id.mainactivitylistview);
   //Adding data to arraylist to be passed to ArrayAdapter. u can use arrays also.
         myitems.add("Christ Redeemer: Rio de Janeiro Brazil"));
         myitems.add("Great Wall of China: China");
         myitems.add("Machu Picchu: Peru");
         myitems.add("Petra: Jordan");
         myitems.add("Pyramid at Chichén Itzá:YucataPeninsula, Mexico");
         myitems.add("Roman Colosseum: Rome, Italy");
         myitems.add("Taj Mahal: Agra, India");


        //Creating Adapter object for setting to listview
        ArrayAdapter adapter=new ArrayAdapter<String>        (MainActivity.this,android.R.layout.simple_list_item_1,android.R.id.text1,myitems);
        mainactivity.setAdapter(adapter);
      }
 @Override 
public boolean onCreateOptionsMenu(Menu menu) { 
// Inflate the menu; this adds items to the action bar if it is present. 
//getMenuInflater().inflate(R.menu.menu_main, menu); 
//this shows three d ots at right corner on click settings open return true; 
} 
@Override 
public boolean onOptionsItemSelected(MenuItem item) {
 // Handle action bar item clicks here. The action bar will
 // automatically handle clicks on the Home/Up button, so long 
// as you specify a parent activity in AndroidManifest.xml. 
int id = item.getItemId(); 
//noinspection SimplifiableIfStatement if (id == R.id.action_settings) 
{ 
return true; 
} 
return super.onOptionsItemSelected(item);
 }
 }

//layout file for MainActivity.java

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <ListView
        android:id="@+id/mainactivitylistview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:divider="@android:color/black"
        android:dividerHeight="2dp"></ListView>

</RelativeLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidruler.simplelistview" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".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>

 

Android Listview With Image And TextView Example/Tutorial

For Custom Listview, we need the following:-

  1. MainActivity class containing  Listview and will be the main screen.
  2. Create Model class to save data for each row like in this example I created MyItem class
  3. Pass this Model class object to ArrayList to generate each row item of Listview.
  4. Create CustomAdapter class to have a view for each row as required in this example I created MyAdapter class to generate a view for each row.
  5. We need two layouts one for MainActivity class containing listview and other for CustomAdapter which we need for each row of the listview. we can create a view for CustomAdapter according to our requirement.

//Main Activity

MainActivity.java

package com.androidruler.customlistview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ListView mainactivity;
    // creating arraylist of MyItem type to set to adapter
    ArrayList<MyItem> myitems=new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mainactivity=(ListView)findViewById(R.id.mainactivitylistview);
    //Adding data i.e images and title to be set to adapter to populate list view
   //here i am passing image id from drawable and string as to be set as title as   
   // a parameter to MyItem Constructor as our ArrayList is type of  MyItem
       
 myitems.add(new MyItem(R.drawable.christ_brazil,"Christ Redeemer: Rio de Janeiro
Brazil"));
 myitems.add(new MyItem(R.drawable.greatwall_china,"Great Wall of China: China"));
 myitems.add(new MyItem(R.drawable.machu_peru,"Machu Picchu: Peru"));
 myitems.add(new MyItem(R.drawable.petra_jorden,"Petra: Jordan"));
 myitems.add(new MyItem(R.drawable.pyramid_mexico,"Pyramid at Chichén Itzá:YucataPeninsula, Mexico"));
 myitems.add(new MyItem(R.drawable.roman_rome,"Roman Colosseum: Rome, Italy"));
 myitems.add(new MyItem(R.drawable.taj_india,"Taj Mahal: Agra, India"));


        //Creating Adapter object for setting to listview
        MyAdapter adapter=new MyAdapter(MainActivity.this,myitems);
        mainactivity.setAdapter(adapter);
// Handle Listview click
  mainactivity.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //Perform click events
        
        MyItem myitem=(MyItem)myitems.get(position);
        
        String title=myitem.getImageheading();
    }
});
} 
@Override 
public boolean onCreateOptionsMenu(Menu menu) {
 // Inflate the menu; this adds items to the action bar if it is present. 
//getMenuInflater().inflate(R.menu.menu_main, menu);
 //this shows three dots at right corner on click settings open
 return true;
 }

 @Override 
public boolean onOptionsItemSelected(MenuItem item) {
 // Handle action bar item clicks here. The action bar will
 // automatically handle clicks on the Home/Up button, so long 
// as you specify a parent activity in AndroidManifest.xml. 
int id = item.getItemId();
 //noinspection SimplifiableIfStatement
 if (id == R.id.action_settings)
 { return true;
 } 
return super.onOptionsItemSelected(item);
 } 
}

 

//Model Class whose objects we pass in ArrayList

MyItem.java

public class MyItem {

    private int imageid;
    private String imageheading="";

    public MyItem(int id,String title)
    {
        imageid=id;
        imageheading=title;
    }

    public int getImageid() {
        return imageid;
    }

    public String getImageheading() {
        return imageheading;
    }

    public void setImageheading(String imageheading) {
        this.imageheading = imageheading;
    }

    public void setImageid(int imageid) {

        this.imageid = imageid;
    }
}

//Custom Adapter extends BaseAdapter

MyAdapter.java

public class MyAdapter extends BaseAdapter {

    Context context;
    ArrayList<MyItem> listforview;
    LayoutInflater inflator=null;
    View v;
    ViewHolder vholder;
    //Constructor
    public MyAdapter(Context con,ArrayList<MyItem> list)
    {
        super();
        context=con;
        listforview=list;
        inflator=LayoutInflater.from(con);
    }

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

    // return size of list
    @Override
    public int getCount() {
        return listforview.size();
    }

    //get Object from each position
    @Override
    public Object getItem(int position) {
        return listforview.get(position);
    }

    //Viewholder class to contain inflated xml views
    private  class ViewHolder
    {
        TextView title;
        ImageView image;
    }
    // Called for each view
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        v=convertView;
        if(convertView==null)
        {
            //inflate the view for each row of listview
            v=inflator.inflate(R.layout.myadapter,null);
            //ViewHolder object to contain myadapter.xml elements
            vholder=new ViewHolder();
            vholder.title=(TextView)v.findViewById(R.id.adaptertextview);
            vholder.image=(ImageView)v.findViewById(R.id.adapterimage);
            //set holder to the view
            v.setTag(vholder);
        }
        else
            vholder=(ViewHolder)v.getTag();


        //getting MyItem Object for each position
        MyItem item=(MyItem)listforview.get(position);

        //setting the values from object to holder views for each row
        vholder.title.setText(item.getImageheading());
        vholder.image.setImageResource(item.getImageid());

        return v;
    }
}

//layout xml file for MainActivity

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <ListView
        android:id="@+id/mainactivitylistview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:divider="@android:color/black"
        android:dividerHeight="2dp"></ListView>

</RelativeLayout>

//layout xml for Adapter

myadapter.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:layout_height="match_parent">
    <ImageView
        android:id="@+id/adapterimage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/adaptertextview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidruler.customlistview" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".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>