ListView Viewholder checkbox state
Here's how I made it work:
First, you need a separate array for your checked state. It has to be the same size as your adapter's getCount()
.
Then on your getView, your checkbox's setOnCheckedChangedListener MUST PRECEED your checkbox.setChecked statements.
example:
holder.checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
isChecked[position] = isChecked;
}
});
holder.checkBox.setChecked(isChecked[position]);
ListView with viewholder and checkbox state save
Here is the proper implementation of your code-
private static class ViewHolder {
CheckBox checkBox;
TextView textView;
}
public ShopAdapter(Context mainContex, ArrayList<ShopItem> shopItems) {
this.mainContex = mainContex;
this.shopItems = shopItems;
}
@Override
public int getCount() {
return shopItems.size();
}
@Override
public Object getItem(int position) {
return shopItems.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ShopItem shopItem = shopItems.get(position);
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
convertView = layoutInflater.inflate(R.layout.shoplist_item, null);
viewHolder.textView = (TextView) item.findViewById(R.id.itemTextView);
viewHolder.checkBox = (CheckBox) item.findViewById(R.id.doneCheckBox);
convertView.setTag(viewHolder);
}
else
{
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.checkBox.setTag(shopItems.get(position));
viewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
shopItem.setDone(true);
viewHolder.textView.setTextColor(mainContex.getResources()
.getColor(R.color.done_text_color));
} else {
shopItem.setDone(false);
viewHolder.textView.setTextColor(mainContex.getResources()
.getColor(R.color.secondary_text));
}
}
});
viewHolder.textView.setText(shopItem.getDescription());
viewHolder.checkBox.setChecked(shopItem.isDone());
return convertView;
}
ListView Checkbox Save State
In getView method, the code should be
if(strDataExist)
{
holder.checkBox.setChecked(true);
}
else
{
holder.checkBox.setChecked(false);
}
Saving State of the checkbox in a custom list view with Checkboxes
Your code is almost right. Just need to do some changes...
Check My code of setOnCheckedChangeListener
for checkbox.. I hope it will work
public class MyCustomBaseAdapter extends BaseAdapter {
private static ArrayList<SearchResults> searchArrayList;
ViewHolder holder;
private LayoutInflater mInflater;
Editor editor;
Context context;
public MyCustomBaseAdapter(Context context, ArrayList<SearchResults> results) {
searchArrayList = results;
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return searchArrayList.size();
}
public Object getItem(int position) {
return searchArrayList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
SharedPreferences sharedPrefs = context.getSharedPreferences("sharedPrefs", Context.MODE_PRIVATE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.custom_row_view, null);
holder = new ViewHolder();
holder.txtName = (TextView) convertView.findViewById(R.id.name);
holder.cB = (CheckBox)convertView.findViewById(R.id.cb_category);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
editor = sharedPrefs.edit();
holder.txtName.setText(searchArrayList.get(position).getName());
holder.cB.setChecked(sharedPrefs.getBoolean("CheckValue"+position, false));
holder.cB.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
editor.putBoolean("CheckValue"+position, isChecked);
editor.commit();
}});
return convertView;
}
static class ViewHolder {
TextView txtName;
CheckBox cB;
}
}
Listview items with checkbox checked at start
Do the following changes:
When you are adding Data to the list of Data.
Data item = new Data();
item.setMenu(obj.getString(TAG_NOMBRE));
item.setId(obj.getString(TAG_ID));
item.setCheckbox(true)
itemList.add(item);
This will initially make the checkbox checked.
Edit:
Update your xml layout. in your CheckBox put this attribute.
android:clickable="false"
Update your list setOnItemClickListener
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
adapter.setCheckBox(position);
}
});
Set checkbox state in listview Adapter
As in Log:
Resources$NotFoundException: String resource ID #0x1
Probably getc1()
and getc2()
methods returning int
type value so system considering both values as ids and trying to find in values resources.
Use String.valueOf
method to show int
value as text in CheckBox
:
holder.txtMake.setText(String.valueOf(currentItem.getMake()));
holder.txtModel.setText(String.valueOf(currentItem.getModel()));
holder.c1.setText(String.valueOf(currentItem.getc1()));
holder.c2.setText(String.valueOf(currentItem.getc2()));
custom ListView with checkboxes checking unchecked items
Your Custom Adapter must implement CompoundButton.OnCheckedChangeListener
. Use a SparseBooleanArray.
Then
cb.setChecked(mCheckStates.get(position, false)); // cb is checkbox
cb.setOnCheckedChangeListener(this);
Then use the checked state to set text to check box
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
Discussion on the topic @
https://groups.google.com/forum/?fromgroups#!topic/android-developers/No0LrgJ6q2M
Example:
Use a ViewHolder
. The below example does not use a View Holder.
There is a Button at the bottom of the screen. When you check the check boxes items of the checked rows are displayed in a toast when you click the button at the bottom.
Use the below and modify according to your requirements.
public class MainActivity extends Activity implements
AdapterView.OnItemClickListener {
int count;
private CheckBoxAdapter mCheckBoxAdapter;
String[] GENRES = new String[] {
"Action", "Adventure", "Animation", "Children", "Comedy",
"Documentary", "Drama",
"Foreign", "History", "Independent", "Romance", "Sci-Fi",
"Television", "Thriller"
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView listView = (ListView) findViewById(R.id.lv);
listView.setItemsCanFocus(false);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(this);
mCheckBoxAdapter = new CheckBoxAdapter(this, GENRES);
listView.setAdapter(mCheckBoxAdapter);
Button b= (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
StringBuilder result = new StringBuilder();
for(int i=0;i<mCheckBoxAdapter.mCheckStates.size();i++)
{
if(mCheckBoxAdapter.mCheckStates.get(i)==true)
{
result.append(GENRES[i]);
result.append("\n");
}
}
Toast.makeText(MainActivity.this, result, 1000).show();
}
});
}
public void onItemClick(AdapterView parent, View view, int
position, long id) {
mCheckBoxAdapter.toggle(position);
}
class CheckBoxAdapter extends ArrayAdapter implements CompoundButton.OnCheckedChangeListener
{ private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1,tv;
CheckBox cb;
String[] gen;
CheckBoxAdapter(MainActivity context, String[] genres)
{
super(context,0,genres);
mCheckStates = new SparseBooleanArray(genres.length);
mInflater = (LayoutInflater)MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
gen= genres;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return gen.length;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = mInflater.inflate(R.layout.checkbox, null);
tv= (TextView) vi.findViewById(R.id.textView1);
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText("Name :"+ gen [position]);
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
}
Related Topics
Automatically Log Android Lifecycle Events Using Activitylifecyclecallbacks
How to Close Another App in Android
Rotate Marker and Move Animation on Map Like Uber Android
How to Make Burst Mode Available to Camera
Android Java.Net.Unknownhostexception: Host Is Unresolved (Strategy Question)
How Does One Configure Rjava on Osx to Select the Right Jvm -- .Jinit() Failing
What Is the Equivalent of a Java Hashmap<String,Integer> in Swift
Why Would One Declare an Immutable Class Final in Java
Java Hotspot(Tm) 64-Bit Server Vm Warning: Ignoring Option Maxpermsize
Difference Between Google() and Maven { Url 'Https://Maven.Google.Com' }
Why Menuitemcompat.Getactionprovider Returns Null
How to Implement the Android Actionbar Back Button
Android Color Between Two Colors, Based on Percentage