Reputation: 12424
I got a ListActivity
with list items I've created. Each item got a CheckBox
in it. In addition, the layout got a button which is suppose to simply check all the check boxes, yet it's not working even though the OnClickListener
of the button is being called.
This a method called from the list adapter:
public void ChangeAllCheckStatus(boolean checked)
{
synchronized (items)
{
for (ItemData item : items)
{
item.checked= checked;
}
}
notifyDataSetChanged();
}
And this is the getView
method:
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
View vi = convertView;
if (vi == null)
{
vi = m_inflater.inflate(R.layout.myItem, null);
}
TextView nameTextView = (TextView) vi.findViewById(R.id.firstText);
TextView addressTextView = (TextView) vi.findViewById(R.id.secondText);
CheckBox cb = (CheckBox) vi.findViewById(R.id.the_checkBox);
nameTextView.setText(items.get(position).string1);
addressTextView.setText(items.get(position).string2);
cb.setSelected(items.get(position).checked);
return vi;
}
Is there something wrong with how I'm trying to check all the checkboxes?
Upvotes: 1
Views: 54
Reputation: 157437
listItem = myList.getAdapter().getView(i, null, null);
is wrong. You shouldn't access the ListView
's items directly. You should be encapsulate the checked status of every single item in the dataset, and let getView
make its work.
Assuming that you have a boolean status;
member in your ListView
's item, you could add a method in your adapter,
public void checkAll() {
synchronized(items) {
for (Item item : items) {
item.status = true;
}
}
notifyDataSetChanged();
}
Edit:
It got an adapter which extends BaseAdapter which also receives 2 arrays of strings as the values. It creates the view at a specific position simply by setting 2 text boxes with the corresponding values from these 2 arrays.
Instead of having two arrays, you could use a small class which encapsulates the information you need. E.g
public class Item {
public String mFirstString;
public String mSecondString;
public boolean mStatus;
}
and feed the BaseAdapter
with a collection of this class. E.g
ArrayList<Item> mItems = new ArrayList<>();
getItem will return mItem.get(position)
, and on getView you'll set the text and the checkbox. E.g.
Item item = getItem(position);
CheckBox cb = (CheckBox) rootView.findViewById(R.id.the_checkBox);
cb.setChecked(item.mStatus);
Upvotes: 1
Reputation: 44118
You don't fetch the views from an adapter. The ListView
does that.
Instead you can loop them via a ListView
like this:
ListView lv;
int itemCount = lv.getCount();
for (int i=0; i<itemCount; ++i) {
CheckBox cb = (CheckBox) lv.getChildAt(i).findViewById(R.id.the_checkBox);
cb.setChecked(true);
}
Upvotes: 2