1

I have a list view inside that i have Section header with check box. If i will click on header check box then all the child check boxes should be checked.If i am keeping the check box inside the list view then i am facing problem.I have attached the image exactly what i need to implement.This is my code which i am using for creating list view Listview with section view

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ListViewCheckboxesActivity extends Activity {

 MyCustomAdapter dataAdapter = null;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  //Generate list View from ArrayList
  displayListView();

  checkButtonClick();

 }

 private void displayListView() {

  //Array list of countries
  ArrayList<Country> countryList = new ArrayList<Country>();
  Country country = new Country("AFG","Afghanistan",false);
  countryList.add(country);
  country = new Country("ALB","Albania",true);
  countryList.add(country);
  country = new Country("DZA","Algeria",false);
  countryList.add(country);
  country = new Country("ASM","American Samoa",true);
  countryList.add(country);
  country = new Country("AND","Andorra",true);
  countryList.add(country);
  country = new Country("AGO","Angola",false);
  countryList.add(country);
  country = new Country("AIA","Anguilla",false);
  countryList.add(country);

  //create an ArrayAdaptar from the String Array
  dataAdapter = new MyCustomAdapter(this,
    R.layout.country_info, countryList);
  ListView listView = (ListView) findViewById(R.id.listView1);
  // Assign adapter to ListView
  listView.setAdapter(dataAdapter);


  listView.setOnItemClickListener(new OnItemClickListener() {
   public void onItemClick(AdapterView<?> parent, View view,
     int position, long id) {
    // When clicked, show a toast with the TextView text
    Country country = (Country) parent.getItemAtPosition(position);
    Toast.makeText(getApplicationContext(),
      "Clicked on Row: " + country.getName(), 
      Toast.LENGTH_LONG).show();
   }
  });

 }

 private class MyCustomAdapter extends ArrayAdapter<Country> {

  private ArrayList<Country> countryList;

  public MyCustomAdapter(Context context, int textViewResourceId, 
    ArrayList<Country> countryList) {
   super(context, textViewResourceId, countryList);
   this.countryList = new ArrayList<Country>();
   this.countryList.addAll(countryList);
  }

  private class ViewHolder {
   TextView code;
   CheckBox name;
  }

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

   ViewHolder holder = null;
   Log.v("ConvertView", String.valueOf(position));

   if (convertView == null) {
   LayoutInflater vi = (LayoutInflater)getSystemService(
     Context.LAYOUT_INFLATER_SERVICE);
   convertView = vi.inflate(R.layout.country_info, null);

   holder = new ViewHolder();
   holder.code = (TextView) convertView.findViewById(R.id.code);
   holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1);
   convertView.setTag(holder);

    holder.name.setOnClickListener( new View.OnClickListener() {  
     public void onClick(View v) {  
      CheckBox cb = (CheckBox) v ;  
      Country country = (Country) cb.getTag();  
      Toast.makeText(getApplicationContext(),
       "Clicked on Checkbox: " + cb.getText() +
       " is " + cb.isChecked(), 
       Toast.LENGTH_LONG).show();
      country.setSelected(cb.isChecked());
     }  
    });  
   } 
   else {
    holder = (ViewHolder) convertView.getTag();
   }

   Country country = countryList.get(position);
   holder.code.setText(" (" +  country.getCode() + ")");
   holder.name.setText(country.getName());
   holder.name.setChecked(country.isSelected());
   holder.name.setTag(country);

   return convertView;

  }

 }

 private void checkButtonClick() {


  Button myButton = (Button) findViewById(R.id.findSelected);
  myButton.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {

    StringBuffer responseText = new StringBuffer();
    responseText.append("The following were selected...\n");

    ArrayList<Country> countryList = dataAdapter.countryList;
    for(int i=0;i<countryList.size();i++){
     Country country = countryList.get(i);
     if(country.isSelected()){
      responseText.append("\n" + country.getName());
     }
    }

    Toast.makeText(getApplicationContext(),
      responseText, Toast.LENGTH_LONG).show();

   }
  });

 }

}

Like this image i heed to be implement

Munim
  • 2,626
  • 1
  • 19
  • 28
Kumar
  • 442
  • 1
  • 9
  • 19
  • Code is saying adapter for Country but image shows its for something different. #Confusing – Paresh Mayani Feb 13 '13 at 07:04
  • It may not be header...they might have removed the header !! Those might be the List with CheckBoxes...See this on how to remove header -- http://stackoverflow.com/questions/2591036/how-to-hide-the-title-bar-for-an-activity-in-xml-with-existing-custom-theme – Name is Nilay Feb 13 '13 at 07:08
  • yes because i have given a design not my app screen shoot and i need to implement like this design. – Kumar Feb 13 '13 at 07:09
  • are you trying to check all child of particular section if suppose `Camera` is check then all its child too checked, is it? – RobinHood Feb 13 '13 at 07:13
  • Yes right if camera is select then its all child should be check. – Kumar Feb 13 '13 at 07:22

1 Answers1

0

Well you haven't posted your real code otherwise I would have told you exact solution. Now based on your sample code, all I can suggest is look out for the line which is responsible for setting checkbox state in getview method:

holder.name.setChecked(country.isSelected());

Now on your header checkbox click listener, all you have to do is set that parameter to true. Based on example it will be country.setSelected(true); for all items which should be checked on header click.

Then call

dataAdapter.notifyDataSetChanged();

It will refresh your listview and mark all those checkboxes as selected.

EDIT:

Here is working code to select all items under a header using SeparatedListAdapter:

ListSample.java

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ListSample extends Activity implements HeaderClickListener
    {

        public final static String ITEM_TITLE = "title";
        public final static String ITEM_CAPTION = "caption";

        // SectionHeaders
        private final static String[] days = new String[]{"Mon", "Tue", "Wed", "Thur", "Fri"};

        // MENU - ListView
        private ListView addJournalEntryItem;

        // Adapter for ListView Contents
        private SeparatedListAdapter adapter;

        // ListView Contents
        private ListView journalListView;

        public Map<String, ?> createItem(String title, String caption)
            {
                Map<String, String> item = new HashMap<String, String>();
                item.put(ITEM_TITLE, title);
                item.put(ITEM_CAPTION, caption);
                return item;
            }

        @Override
        public void onCreate(Bundle icicle)
            {
                super.onCreate(icicle);
                // Sets the View Layer
                setContentView(R.layout.main);
                // Interactive Tools
                final ArrayAdapter<String> journalEntryAdapter = new ArrayAdapter<String>(this, R.layout.add_journalentry_menuitem, new String[]{"Add Journal Entry"});
                // AddJournalEntryItem
                addJournalEntryItem = (ListView) this.findViewById(R.id.add_journalentry_menuitem);
                addJournalEntryItem.setAdapter(journalEntryAdapter);
                addJournalEntryItem.setOnItemClickListener(new OnItemClickListener()
                    {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long duration)
                            {
                                String item = journalEntryAdapter.getItem(position);
                                Toast.makeText(getApplicationContext(), item, Toast.LENGTH_SHORT).show();
                            }
                    });

                // Create the ListView Adapter
                adapter = new SeparatedListAdapter(this);
                // Add Sections
                for (int i = 0; i < days.length; i++)
                {
                    ArrayList<CategoryList> categoryLists = new ArrayList<CategoryList>();
                    for(int j = 0; j < 10; j++)
                    {
                    CategoryList categoryList = new CategoryList();
                    categoryList.setSelected(false);
                    categoryList.setTitle(days[i] + j);
                    categoryLists.add(categoryList);
                    }
                    CustomBaseAdpater baseAdpater = new CustomBaseAdpater(categoryLists);
                    adapter.addSection(days[i], baseAdpater);
                }

                // Get a reference to the ListView holder
                journalListView = (ListView) this.findViewById(R.id.list_journal);

                // Set the adapter on the ListView holder
                journalListView.setAdapter(adapter);

                // Listen for Click events
                journalListView.setOnItemClickListener(new OnItemClickListener()
                    {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long duration)
                            {
                                String item = (String) adapter.getItem(position);
                                Toast.makeText(getApplicationContext(), item, Toast.LENGTH_SHORT).show();
                            }
                    });
            }

        private class CustomBaseAdpater extends BaseAdapter
        {

            ArrayList<CategoryList> list = null;
            CustomBaseAdpater( ArrayList<CategoryList> categoryLists )
            {
                this.list = categoryLists;
            }

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

            @Override
            public Object getItem(int position) {
                return null;
            }

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

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                ViewHolder viewHolder = null;
                if (null == convertView)
                {
                    viewHolder = new ViewHolder();
                    LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
                    convertView = inflater.inflate(R.layout.item_row, null);
                    viewHolder.checkBox = (CheckBox) convertView.findViewById(R.id.checkItem);
                    viewHolder.textView = (TextView) convertView.findViewById(R.id.textTitle);
                    convertView.setTag(viewHolder);
                }
                else
                    viewHolder = (ViewHolder) convertView.getTag();

                viewHolder.checkBox.setChecked(list.get(position).isSelected());
                viewHolder.textView.setText(list.get(position).getTitle());

                return convertView;
            }

            private class ViewHolder
            {
                CheckBox checkBox;
                TextView textView;
            }
            private void checkCompleteSection()
            {
                for(CategoryList categoryList : this.list)
                categoryList.setSelected(true);
            }
        }

        @Override
        public void refreshSection(String sectionName) {
            if(adapter.sections.get(sectionName) != null)
            {
                ((CustomBaseAdpater)(adapter.sections.get(sectionName))).checkCompleteSection();
                adapter.notifyDataSetChanged();
            }
        }

    }

SeparatedListAdapter.java

import java.util.LinkedHashMap;
import java.util.Map;

import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.Toast;

public class SeparatedListAdapter extends BaseAdapter
    {
        public final Map<String, Adapter> sections = new LinkedHashMap<String, Adapter>();
        public final ArrayAdapter<String> headers;
        public final static int TYPE_SECTION_HEADER = 0;
        Context context = null;

        public SeparatedListAdapter(Context context)
            {
                headers = new ArrayAdapter<String>(context, R.layout.list_header);
                this.context = context;
            }

        public void addSection(String section, Adapter adapter)
            {
                this.headers.add(section);
                this.sections.put(section, adapter);
            }

        public Object getItem(int position)
            {
                for (Object section : this.sections.keySet())
                    {
                        Adapter adapter = sections.get(section);
                        int size = adapter.getCount() + 1;

                        // check if position inside this section
                        if (position == 0) return section;
                        if (position < size) return adapter.getItem(position - 1);

                        // otherwise jump into next section
                        position -= size;
                    }
                return null;
            }

        public int getCount()
            {
                // total together all sections, plus one for each section header
                int total = 0;
                for (Adapter adapter : this.sections.values())
                    total += adapter.getCount() + 1;
                return total;
            }

        @Override
        public int getViewTypeCount()
            {
                // assume that headers count as one, then total all sections
                int total = 1;
                for (Adapter adapter : this.sections.values())
                    total += adapter.getViewTypeCount();
                return total;
            }

        @Override
        public int getItemViewType(int position)
            {
                int type = 1;
                for (Object section : this.sections.keySet())
                    {
                        Adapter adapter = sections.get(section);
                        int size = adapter.getCount() + 1;

                        // check if position inside this section
                        if (position == 0) return TYPE_SECTION_HEADER;
                        if (position < size) return type + adapter.getItemViewType(position - 1);

                        // otherwise jump into next section
                        position -= size;
                        type += adapter.getViewTypeCount();
                    }
                return -1;
            }

        public boolean areAllItemsSelectable()
            {
                return false;
            }

        @Override
        public boolean isEnabled(int position)
            {
                return (getItemViewType(position) != TYPE_SECTION_HEADER);
            }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
            {
                int sectionnum = 0;
                for (Object section : this.sections.keySet())
                    {
                        Adapter adapter = sections.get(section);
                        int size = adapter.getCount() + 1;

                        // check if position inside this section
                        if (position == 0) 
                        {
                         View headerView = headers.getView(sectionnum, convertView, parent);
                         headerView.setTag(section);
                         headerView.setOnClickListener(new OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    String sectionName = v.getTag().toString();
                                Toast.makeText(context,  sectionName ,2000).show();
                                ((HeaderClickListener) context).refreshSection(sectionName);    
                                }
                            });
                         return headerView;
                        }
                        if (position < size) return adapter.getView(position - 1, convertView, parent);

                        // otherwise jump into next section
                        position -= size;
                        sectionnum++;
                    }
                return null;
            }

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

    }

item_row.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="horizontal" >
    <CheckBox 
        android:id="@+id/checkItem"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        />
    <TextView 
        android:id="@+id/textTitle"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />

</LinearLayout>
Sourab Sharma
  • 2,940
  • 1
  • 25
  • 38
  • But how to implement header section with check box. – Kumar Feb 13 '13 at 07:52
  • I need your real code to help you out. Your arraylist, getview and onclicklistener. All I can suggest without any code that create an additional parameter isHeader. If it is true, inflate it with different layout, the one with dark background, otherwise with the one with light background so it look like it is in the image. Now on row click determine if it is header clicked , set checked all items isSelected = true until next header in the list. – Sourab Sharma Feb 13 '13 at 07:58
  • You can see this link i am following this link to implement Header section. "http://w2davids.wordpress.com/android-sectioned-headers-in-listviews/" – Kumar Feb 13 '13 at 08:58