ListView adapter behaves strangely - android

ListView adapter does strange things. Method getChecked() (adapter code shown below) does not return the value that I expect. As if he is late by one step.
For understanding, I will explain: I am using a custom ListView, every item contain one CheckBox (and other Views). I want to make when I press the button to show the position of the checked elements. This makes the method getChecked().
But the following happens: I check the 2nd and the 4th list items and click on the button, the result - [], then I check the 5th item, the result - [2, 4], then I clean all CheckBoxes, result [2, 4, 5] when I click the button again, I receive - []. Result is late by one step.
public class ContactAdapter extends BaseAdapter {
private LayoutInflater inflater;
private ArrayList<Contact> contacts;
private boolean isCheckBoxVisible;
private View view;
private int[] colors = {Color.BLACK, Color.BLUE, Color.RED, Color.GRAY, Color.GREEN};
private int currentMaleColor;
private int currentFemaleColor;
public ContactAdapter(Context context, ArrayList<Contact> contacts) {
this.contacts = contacts;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
isCheckBoxVisible = false;
setColors();
}
#Override
public int getCount() {
return contacts.size();
}
#Override
public Object getItem(int position) {
return contacts.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private Contact getContact(int position) {
return (Contact) getItem(position);
}
public void setCheckBoxVisibility(boolean isVisible) {
isCheckBoxVisible = isVisible;
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
view = convertView;
if (view == null) {
view = inflater.inflate(R.layout.contact_item, parent, false);
}
CheckBox cb = (CheckBox) view.findViewById(R.id.lv_box);
if (isCheckBoxVisible) {
cb.setVisibility(View.VISIBLE);
} else {
cb.setVisibility(View.INVISIBLE);
}
Contact c = getContact(position);
((TextView) view.findViewById(R.id.lv_name)).setText(c.getName() + " " + c.getSurname());
((ImageView) view.findViewById(R.id.lv_img)).setImageBitmap(c.getPhoto());
if (c.getSex().equals("Man")) {
view.setBackgroundColor(currentMaleColor);
} else {
view.setBackgroundColor(currentFemaleColor);
}
boolean isCheck = ((CheckBox) view.findViewById(R.id.lv_box)).isChecked();
contacts.get(position).setChecked(isCheck);
return view;
}
public ArrayList<Integer> getChecked() {
notifyDataSetChanged();
ArrayList<Integer> IDs = new ArrayList<Integer>();
for (Contact c : contacts) {
if (c.isChecked()) IDs.add(c.getID());
}
return IDs;
}
private void setColors() {
int colorM = Integer.parseInt(MainActivity.sp.getString("lp_colorM", "0"));
int colorW = Integer.parseInt(MainActivity.sp.getString("lp_colorW", "0"));
currentMaleColor = colors[colorM];
currentFemaleColor = colors[colorW];
}
}
In my activity I use my adapter, like so:
#Override
protected void onResume() {
super.onResume();
adapter = new ContactAdapter(getApplicationContext(), contacts);
list.setAdapter(adapter);
}
My button's code:
ArrayList<Integer> al = adapter.getChecked();
Toast.makeText(this, al.toString(), Toast.LENGTH_LONG).show();
What do you think about this? I will be glad of any help.

Try to get State of view if convertView == null
if (convertView == null) {
holder = new Holder();
convertView = mInflator.inflate(R.layout.row_viewproduct, null);
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
// set the data to view from holder

This is not the answer but want say you can use below
private void setColors() {
int colorM = Integer.parseInt(MainActivity.sp.getString("lp_colorM", "0"));
int colorW = Integer.parseInt(MainActivity.sp.getString("lp_colorW", "0"));
if(colorM < 5){
currentMaleColor = colors[colorM];
}
if(colorW < 5){
currentFemaleColor = colors[colorM];
}
}
To answer your question look at the view holder pattern
http://ricston.com/blog/optimising-listview-viewholder-pattern/

On the advice of njzk2, I changed it:
boolean isCheck = ((CheckBox) view.findViewById(R.id.lv_box)).isChecked();
contacts.get(position).setChecked(isCheck);
At this:
CheckBox checkBox = (CheckBox) view.findViewById(R.id.lv_box);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
contacts.get(position).setChecked(isChecked);
}
});
Now it works :)

Related

Select only one checkbox/radiobutton in the same row and column with Two checkbox/Radio button in a row using Listview Android

I have used Customized Listview using Adapter class in the Adapter class Two checkbox in a ROW For this I need Select Only one check box Either Checkbox1 Row/Column same as Checkbox 2.
For Example I have 5 rows in a Listview Totally 10 Checkbox inside Listview Out 10 Only one select at a Time all Other should unselect
Any idea About that I tried Lot but select only Checkbox1 column only
Please help
public class ListViewAdapter extends ArrayAdapter<Friend> {
private List<Friend> myFriends;
private Activity activity;
private int selectedPosition = -1;
String flag="";
String[]ids=new String[100];
String[]ids1=new String[100];
public ListViewAdapter(Activity context, int resource, List<Friend> objects) {
super(context, resource, objects);
this.activity = context;
this.myFriends = objects;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
// If holder not exist then locate all view from UI file.
if (convertView == null) {
// inflate UI from XML file
convertView = inflater.inflate(R.layout.item_listview, parent, false);
// get all UI view
holder = new ViewHolder(convertView);
// set tag for holder
convertView.setTag(holder);
} else {
// if holder created, get tag from view
holder = (ViewHolder) convertView.getTag();
}
holder.checkBox.setTag(position); // This line is important.
holder.checkBox1.setTag(position + 100);
holder.friendName.setText(getItem(position).getName());
holder.rdgrp.setTag(position);
ids[position]=holder.checkBox.getTag().toString();
ids1[position]=holder.rdgrp.getTag().toString();
// System.out.println("praveen"+ids[position]);
if (position == selectedPosition) {
holder.rdgrp.setActivated(true);
} else holder.rdgrp.setActivated(false);
if( holder.checkBox.getTag().equles(position)){
holder.checkBox.setOnClickListener(onStateChangedListener(holder.checkBox, position));
}else{
holder.checkBox1.setOnClickListener(onStateChangedListener(holder.checkBox1, position));
}
return convertView;
}
public View.OnClickListener onStateChangedListener(final RadioGroup gry, final int position ){
return new View.OnClickListener() {
#Override
public void onClick(View v) {
if (gry.isClickable()) {
selectedPosition = position;
} else {
selectedPosition = -1;
}
notifyDataSetChanged();
}
};
}
private static class ViewHolder {
private TextView friendName;
private CheckBox checkBox,checkBox1;
public ViewHolder(View v) {
checkBox = (CheckBox) v.findViewById(R.id.check);
checkBox1 = (CheckBox) v.findViewById(R.id.check1);
friendName = (TextView) v.findViewById(R.id.name);
}
}
}
you can use group for check box of a single row of list view which has two check box and then apply following line of code
"listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE)"
Try with following code:
public class CustomAdapter extends BaseAdapter{
int selectedPosition = -1; // row position
int selectedCheckbox = -1; // 1 for 1st, 2 for 2nd on each row
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(position == selectedPosition){
if(selectedCheckbox == 1){
checkbox1.setChecked(true);
checkbox2.setChecked(false);
} else if(selectedCheckbox == 2){
chkbox1.setChecked(false);
chkbox2.setChecked(true);
}
} else{
checkbox1.setChecked(false);
checkbox2.setChecked(false);
}
checkbox1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
selectedPosition = position;
selectedCheckbox = 1;
} else{
selectedPosition = -1;
selectedCheckbox = -1;
}
notifyDataSetChanged();
}
});
checkbox2.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
selectedPosition = position;
selectedCheckbox = 2;
} else{
selectedPosition = -1;
selectedCheckbox = -1;
}
notifyDataSetChanged();
}
});
return convertView;
}
}
Hope, it will help you!

invalid Data in listview selection

I have a list view of the emails of all the contacts in the phonebook.My list is a custom listview with a checkbox.Now the problem is as follows.
For eg i have 20 emails in the list.If i select the first email say "A" in the list and then scrolls the list,other emails are also getting selected by itself.Also if i again scroll back to the list ,my selected email "A" is being deselected by it own. I dnot know why this is occuring
CustomList
public class EmailListAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> data;
DbHandler dbHandler;
public EmailListAdapter(Context context, ArrayList<String> data) {
this.context = context;
this.data = data;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
final ViewHolder holder;
dbHandler = new DbHandler(context);
if (view == null) {
holder = new ViewHolder();
view = LayoutInflater.from(context).inflate(R.layout.email_custom_list, viewGroup, false);
holder.tvContact = (TextView) view.findViewById(R.id.tv_email_name);
holder.checkBox = (CheckBox) view.findViewById(R.id.cb_email_checkbox);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (compoundButton == holder.checkBox) {
if (b) {
// dbHandler.updateContactList(data.get(i).getUserID(), 1);
} else {
// dbHandler.updateContactList(data.get(i).getUserID(), 0);
}
}
}
});
holder.tvContact.setText(data.get(i));
return view;
}
private class ViewHolder {
TextView tvContact;
CheckBox checkBox;
}
The Adapter is recycling your views. Let's look at the following example:
Your ListView shows 10 rows at once and the first row has a blue background color. Now If you start scrolling the 11th row will become visible and the first will be hidden.
Internally the system recycles your first row and uses it as the 11th. So your 11th row will be blue as well.
So in order to fix this you have to set the background color each time in your getView(...) function. In your example you have to save the state of the different CheckBoxes manually and reapply them in the getView-function.
Edit
Just found this post on StackOverflow. It's discussing this topic even more detailed: How ListView's recycling mechanism works
Solution
Following just the relevant parts:
private int[] mStates;
public EmailListAdapter(Context context, ArrayList<String> data) {
this.context = context;
this.data = data;
mStates = new int[data.size()];
}
#Override
public View getView(final int position, View view, ViewGroup viewGroup) {
//...
if (mStates[position] == 0) {
holder.checkbox.setChecked(false);
} else {
holder.checkbox.setChecked(true);
}
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (compoundButton == holder.checkBox) {
if (b) {
mStates[position] = 1;
//dbHandler.updateContactList(data.get(i).getUserID(), 1);
} else {
mStates[position] = 0;
//dbHandler.updateContactList(data.get(i).getUserID(), 0);
}
}
}
});
//...
}
Since you are using a view holder your check box get reused while scrolling.The same check box at top comes again at bottom while you scroll when you use view holder.
And when you scroll back to top the check box comes back may not be old one.
So you have to save each checklists state to a list and use it according to position as your text view.
Solved Ans
public class EmailListAdapter extends BaseAdapter {
private Context context;
private ArrayList<EmailModel> data;
DbHandler dbHandler;
int[] emails;
ArrayList<String> emailSeperated;
public EmailListAdapter(Context context, ArrayList<EmailModel> data) {
this.context = context;
this.data = data;
emails = new int[data.size()];
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
final ViewHolder holder;
dbHandler = new DbHandler(context);
emailSeperated = new ArrayList<String>();
if (view == null) {
holder = new ViewHolder();
view = LayoutInflater.from(context).inflate(R.layout.email_custom_list, viewGroup, false);
holder.tvContact = (TextView) view.findViewById(R.id.tv_email_name);
holder.checkBox = (CheckBox) view.findViewById(R.id.cb_email_checkbox);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// if (emails[i] == 0) {
// holder.checkBox.setChecked(false);
// } else {
// holder.checkBox.setChecked(true);
// }
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (compoundButton == holder.checkBox) {
if (b) {
emails[i] = 1;
//dbHandler.updateContactList(data.get(i).getUserID(), 1);
emailSeperated.add(data.get(i).getEmail());
Log.e("Email values", emailSeperated.toString());
//
} else {
emails[i] = 0;
emailSeperated.remove(data.get(i).getEmail());
Log.e("Email values", emailSeperated.toString());
}
}
}
}
);
if (emails[i] == 0) {
holder.checkBox.setChecked(false);
} else {
holder.checkBox.setChecked(true);
}
holder.tvContact.setText(data.get(i).
getEmail()
);
return view;
}
private class ViewHolder {
TextView tvContact;
CheckBox checkBox;
}
}

Android: Listview don't save a state of checkbox

I check all topic with similar problem, but I stil stay in deadpoint. I have a listview with contact list, but when i scroll down and scroll up listview don't save a state of my choices. All checkboxes was setting on false. When i debug i see, when i scrolled listview, my onClickListener thinking that checkbox was signed and reset this. I do everything, other array with position boolean, etc etc and I still don't know what to do :( I will be very gratefull for any help:)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
readContacts();
Contact_Database dbhandler = new Contact_Database(
getApplicationContext(), null, null, 1);
numbers.addAll( dbhandler.getAllNumbers());
System.out.println("onCreate");
ListView lv = getListView();
registerForContextMenu(lv);
lv.setTextFilterEnabled(true);
lv.clearChoices();
MyAdapter adapter = (new MyAdapter(this, R.layout.contact_list_sms, contacts));
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
}
/**
* When I destroy intent i send request to database, faster!
*/
#Override
protected void onDestroy() {
super.onDestroy();
for (int i = 0; i < numbers.size(); ++i)
System.out.println("####" + numbers.get(i));
swap_contacts();
}
class MyAdapter extends ArrayAdapter<Contact> {
LayoutInflater inflat;
public MyAdapter(Context context, int textViewResourceId,
ArrayList<Contact> objects) {
super(context, textViewResourceId, objects);
inflat = LayoutInflater.from(context);
System.out.println("LOLLLLL");
notifyDataSetChanged();
}
#Override
public int getItemViewType(int position) {
return (position == this.getCount() - 1) ? 1 : 0;
}
#Override
public int getViewTypeCount() {
return 2;
}
// if that contact exist in database? numbers, in onCreate method
// i init this with saved position from databse
private boolean exist(String x) {
for (int i = 0; i < numbers.size(); i++)
if (numbers.get(i).compareTo(x) == 0)
return true;
return false;
}
#SuppressLint("NewApi")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
System.out.println("ROWS !!! ->" + numbers.size());
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflat.inflate(R.layout.contact_row, null);
holder.textView1 = (TextView) convertView
.findViewById(R.id.name);
holder.textView2 = (TextView) convertView
.findViewById(R.id.number);
holder.on_off = (CheckBox) convertView
.findViewById(R.id.enable);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Contact it = contacts.get(position);
Log.v("XXX", holder.toString());
if (it != null) {
holder.textView1.setText(contacts.get(position).name);
holder.textView2.setText(contacts.get(position).phone);
// update state of checbox from database
if (exist(contacts.get(position).phone))
holder.on_off.setChecked(true);
else
holder.on_off.setChecked(false);
}
final int element_position = position;
holder.on_off
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
// update list when we click on it
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
String nr_telefonu = contacts.get(element_position).phone;
if (isChecked) {
numbers.add(nr_telefonu);
} else {
numbers.remove(nr_telefonu);
}
}
});
return convertView;
}
#Override
public Contact getItem(int position) {
return contacts.get(position);
}
private class ViewHolder {
TextView textView1, textView2;
CheckBox on_off;
public String toString() {
return "-";
}
}
}
List does not save it state while scrolling , because each time new object is created for row item. So you need to explicitly save the state of CheckBox with help of Pojo class(Setter and getter).
in getView() method you need to check the value for each checkbox.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
////////////////////
and on setOnCheckedChangeListener you need to save the state of checkbox
holder.on_off
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
// update list when we click on it
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// need to save the state
for more details please refer to this below blog
http://amitandroid.blogspot.in/2013/03/android-listview-with-checkbox-and.html
you can change it according to your requirement.
Thank's for answer :) I create a array stan with state for every checkbox button. Tommorrow i will try rebuild all my class like the list on the blog, mayby this help me.
But when I do this :
save state:
holder.on_off
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
// update list when we click on it
// this.setChecked(stan[position]);
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
String nr_telefonu = p.get(element_position).phone;
buttonView.setChecked(stan[element_position]);
stan[element_position] = isChecked;
}
});
Refresh state of button
if (it != null) {
holder.textView1.setText(contacts.get(position).name);
holder.textView2.setText(contacts.get(position).phone);
// update state of checbox from database
holder.on_off.setChecked(stan[position]);
}
I still stand In dead point, nothing is changed
I've posted the solution to this problem below which I spent a lot of time finding and it works for me!
public class RowAdapter extends ArrayAdapter<Rows> {
Context context;
int layoutResourceId;
ArrayList<Rows> data;
boolean[] checkBoxState;
RowHolder rowHolder;
public RowAdapter(Context context, int layoutResourceId, ArrayList<Rows> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
checkBoxState = new boolean[data.size()];
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
RowHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new RowHolder();
holder.textView1 = (TextView)row.findViewById(R.id.textView1);
holder.textView2 = (TextView)row.findViewById(R.id.textView2);
holder.textView3 = (TextView)row.findViewById(R.id.textView3);
holder.textView4 = (TextView)row.findViewById(R.id.textView4);
holder.checkBox=(CheckBox) row.findViewById(R.id.checkBox1);
row.setTag(holder);
}
else{
holder = (RowHolder)row.getTag();
}
Rows rows = data.get(position);
holder.textView1.setText(rows.address);
holder.textView2.setText(rows.tenancy);
holder.textView3.setText(rows.location);
holder.textView4.setText(rows.name);
holder.checkBox.setChecked(checkBoxState[position]);
holder.checkBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(((CheckBox)v).isChecked())
checkBoxState[position]=true;
else
checkBoxState[position]=false;
}
});
return row;
}
static class RowHolder
{
TextView textView1;
TextView textView2;
TextView textView3;
TextView textView4;
CheckBox checkBox;
}
}

Android - Remove GridView item from inside getView()?

I need a way to remove an Item from the GridView but this must be done from within the getView() method inside my custom Adapter. Here is my GridView:
Activity:
...
String[] newList;
newList[0] = "Item 1";
newList[1] = "Item 2";
newList[2] = "Item 3";
...
GridView GV = (GridView) getActivity().findViewById(R.id.gv);
GV.setAdapter(new Adapter(getActivity(), newList));
GV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView arg0,
View arg1, int position, long arg3) {
...
}
});
Adapter
public class Adapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mInflator;
private String mEntries[];
public static class ViewHolder {
public TextView myTextView;
}
public Adapter (Context context, String[] entries) {
mContext = context;
mInflator = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mEntries = entries;
}
#Override
public int getCount() {
return mEntries.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView == null) {
convertView = mInflator.inflate(R.layout.gvitemlayout, parent, false);
holder = new ViewHolder();
holder.myTextView = (TextView) convertView.findViewById(R.list.removeItem);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
String string = mEntries[position];
String[] data = string.split("\\.");
if (data.length < 2) {
TextView itemName = (TextView) convertView.findViewById(R.list.itemName);
itemName.setText("");
TextView itemClass = (TextView) convertView.findViewById(R.favlist.itemClass);
itemClass.setText("");
holder.myTextView.setText("");
TextView itemNone = (TextView) convertView.findViewById(R.list.itemNone);
itemNone.setText("No Items");
} else {
TextView itemName = (TextView) convertView.findViewById(R.list.itemName);
itemName.setText(data[1]);
TextView itemClass = (TextView) convertView.findViewById(R.list.itemClass);
itemClass.setText(data[0]);
}
final int info = (Integer) getItem(position);
holder.myTextView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SharedPreferences sP = mContext.getSharedPreferences("fav", mContext.MODE_PRIVATE);
Boolean b = sP.getBoolean(mEntries[info], false);
if (b == true) {
SharedPreferences.Editor editor = sP.edit();
editor.remove(mEntries[info]);
editor.commit();
// REMOVE ITEM CODE NEEDED HERE
}
}
});
return convertView;
}
}
Hope this makes it easier to understand what I need.
This is what I did, there was no need to initialise the 'adapter' variable. Inside the getView() simply do this:
Remove the Item from the list that was used as the data source.
So. if you want to remove Item 2 from the list
String mEntries[] = ITEM1, ITEM2, ITEM3, etc
Do this:
String newList[] = new String[mEntries.length - 1];
int count = 0;
for (int i = 0; i < mEntries.length; i++) {
if (mEntries.length - 1 > 0) {
if (mEntries[i] == mEntries[1]) { // mEntries[1] as the range starts from 0, so 1 would be ITEM2
// SKIP IF MATCHES THE ITEM YO WANT TO REMOVE
} else {
newList[count] = mEntries[i];
count++;
}
}
}
mEntries = newList; // save the new list into mEntries
notifyDataSetChanged(); // notify the changes and the listview/gridview will update
What you are asking for is very possible. You didn't give enough code for it to be clear exactly what's happening, but the code above you posted won't work unless the remove button is an entire view returned by getView in the adapter.
Your getView in your adapter will need to look something like this:
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.grid_view_item, null);
}
Button removeButton = (Button) convertView.findViewById(R.id.remove_button);
removeButton.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
adapter.mThumbIdsList.remove(position);
adapter.notifyDataSetChanged();
}
});
return convertView;
}
Hope this helps. Good luck!

android checkbox is not checked for custom listview when listview is in scrollview

i have implemented custom list view with check box and textviews. It is working fine when list view is not in scroll but if the rows are increased then listviews is in scroll view that time when i click on check box the checked mark is not staying. here is my code, Please suggest me if anything wrong in that code
public class ArchivedAdapter extends ArrayAdapter<MessageBean> {
final ArrayList<MessageBean> updatedList = new ArrayList<MessageBean>();
private List<MessageBean> list;
private TextView officenameView, sentOnView, messageView;
public final static String MY_ACTION = "com.android.threeptalk.broadcast";
private boolean isDeleted = false;
int count = 0;
HashMap<Integer, CheckBox> checkList = new HashMap<Integer, CheckBox>();
public ArchivedAdapter(Context context, int resourseID,
List<MessageBean> list) {
super(context, resourseID, list);
this.list = list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public MessageBean getItem(int arg0) {
return list.get(arg0);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutInflater inflater = (LayoutInflater) this.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.archievedmsgrow, parent, false);
row.setId(position);
Object obj = getItem(position);
if (obj instanceof MessageBean) {
final MessageBean message = (MessageBean) obj;
CheckBox checkBox = (CheckBox) row.findViewById(R.id.checkBox);
officenameView = (TextView) row.findViewById(R.id.officename);
sentOnView = (TextView) row.findViewById(R.id.time);
messageView = (TextView) row.findViewById(R.id.message);
officenameView.setText(message.getOfficeName());
checkList.put(position, checkBox);
checkBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
CheckBox c = (CheckBox) v;
if (c.isChecked()) {
c.setChecked(true);
count++;
updatedList.add(message);
} else {
c.setChecked(false);
count--;
updatedList.remove(message);
updatedList.size());
}
checkedCount(count, updatedList);
}
});
row.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
rowclicked(message, position);
}
});
sentOnView.setText(Common.getAppropriateTimeUsingTimeZone(message
.getmDate()));
if (message.getMessage() != null) {
messageView.setText((message.getMessage()));
} else {
if (message.getMessageType().equals("OPTION")) {
if (message.getOptions() != null
&& message.getOptions().size() > 0) {
String data = message.getOptions().get(0);
if (data != null && !data.equals("")) {
messageView.setText(data);
}
}
}
}
}
return row;
}
protected void messageSelected() {
}
protected void rowclicked(MessageBean message, int position) {
// TODO Auto-generated method stub
}
protected void checkedCount(int count2, ArrayList<MessageBean> updatedList) {
}
}
`
Try this example ListView with CheckBox Scrolling Issue
Seems like you are checking the check status of checkbox inside its onClickListener().
First define an Hashmap or SparseBooleanArray to save your selections.
private HashMap<Integer, Boolean> mSelection = new HashMap<Integer, Boolean>();
Then add the following code to your getView() method.
CheckBox checkBox = (CheckBox) row.findViewById(R.id.checkBox);
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
mSelection.put(position, isChecked);
}
});
if (mSelection.get(position) != null) {
if (mSelection.get(position))
checkBox.setChecked(true);
else
checkBox.setChecked(false);
}
Try this, Assuming that you are using the Custom Adapter for your ListView, you will be able to set Tag for each Item inside your Adapter's getView(),
public View getView(int position, View convertView, ViewGroup parent) {
EvenViewHolder holdereven;
if (convertView == null) {
convertView = mInfaltor.inflate(R.layout.schedule_adapter_view,
null);
holdereven = new EvenViewHolder();
holdereven.time = (TextView) convertView
.findViewById(R.id.time);
holdereven.title = (TextView) convertView
.findViewById(R.id.title);
holdereven.des = (TextView) convertView.findViewById(R.id.des);
convertView.setTag(holdereven);
} else {
holdereven = (EvenViewHolder) convertView.getTag();
}
static class EvenViewHolder {
TextView time, title, des;
}
}

Categories

Resources