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