Automatic uncheck checkboxes when change check in listview - android

I customize a listview with textview and a checkbox. Now i want when change check checkbox different old checked will unchecked ( In listview have only a item checked ). I don't have resolve. And now i need help !
Sorry. I speak English not good
Here ! Code in adapter
public class ListSongCheckDownloadAdapter extends ArrayAdapter<String>
implements OnCheckedChangeListener {
private ArrayList<String> listnameSong;
private Context context;
public SparseBooleanArray mCheckStates;
int layoutResourceId;
public ListSongCheckDownloadAdapter(Context context, int resource,
int textViewResourceId, List<String> objects) {
super(context, resource, textViewResourceId, objects);
this.context = context;
this.layoutResourceId = resource;
this.listnameSong = new ArrayList<String>(objects);
mCheckStates = new SparseBooleanArray(listnameSong.size());
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
ViewHolder viewholder;
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.listsongdownload_layout, null);
viewholder = new ViewHolder();
viewholder.tvNameSong = (TextView) rowView
.findViewById(R.id.nameOfSong);
viewholder.cbChecked = (CheckBox) rowView
.findViewById(R.id.cbCheckSong);
rowView.setTag(viewholder);
} else {
viewholder = (ViewHolder) rowView.getTag();
}
viewholder.tvNameSong.setText(listnameSong.get(position));
viewholder.cbChecked.setTag(position);
viewholder.cbChecked.setChecked(mCheckStates.get(position, false));
viewholder.cbChecked.setOnCheckedChangeListener(this);
return rowView;
}
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));
}
static class ViewHolder {
TextView tvNameSong;
CheckBox cbChecked;
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
And here is Download Activity
public class DownloadAlbumActivity extends Activity implements
OnItemClickListener {
private ArrayList<String> nameSongInList;
private ArrayList<String> linkDownOfAlbum;
ListSongCheckDownloadAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.downloadalbum_layout);
nameSongInList = new ArrayList<String>();
linkDownOfAlbum = new ArrayList<String>();
Intent intent = getIntent();
nameSongInList = intent.getStringArrayListExtra("namesong");
linkDownOfAlbum = intent.getStringArrayListExtra("linkdown");
ImageButton btnChecked = (ImageButton) findViewById(R.id.btnChecked);
ListView lvAdapter = (ListView) findViewById(R.id.lvSongOfAlbum);
lvAdapter.setItemsCanFocus(false);
adapter = new ListSongCheckDownloadAdapter(DownloadAlbumActivity.this,
R.layout.listsongdownload_layout, R.id.tvNameSong,
nameSongInList);
lvAdapter.setAdapter(adapter);
btnChecked.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
String result = "";
for (int i = 0; i < adapter.mCheckStates.size(); i++) {
if (adapter.mCheckStates.get(i) == true) {
result = linkDownOfAlbum.get(i).toString();
}
}
Toast.makeText(DownloadAlbumActivity.this, result,
Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long arg3) {
adapter.toggle(position);
}
}

You could save the ID of the currently checked item in a variable. Then, when another item is checked (inside the listener) you simply uncheck the old one and change the variable to the new ID.

Related

Custom Adapter with check box values is not rechecked when reopen the activity

I have an activity with custom list view with adapter. In which i am selecting many names by checking the check box. when press the OK button,I am getting the selected values back to the previous activity. When reopen the activity,The already selected values in check box is not rechecked again. How to solve this issue?.
Code
public class MultiselectAdapter extends ArrayAdapter<String> implements CompoundButton.OnCheckedChangeListener{
private final LayoutInflater mInflater;
private final Context mContext;
private final List<TeamModel> items = null;
private final int mResource;
SparseBooleanArray mCheckStates;
public String[] teamIDValues;
ArrayList<Object> ListObject;
public MultiselectAdapter(#NonNull Context context, #LayoutRes int resource,
#NonNull ArrayList objects ){
super(context, resource, 0, objects);
mContext = context;
mInflater = LayoutInflater.from(context);
mResource = resource;
ListObject = objects;
mCheckStates = new SparseBooleanArray(ListObject.size());
System.out.println("teh size vaooo --"+mCheckStates.size());
System.out.println("teh objects vaooo --"+objects.size());
}
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
mCheckStates.put((Integer) compoundButton.getTag(), isChecked);
}
static class ViewHolder {
protected TextView name;
protected TextView id;
protected CheckBox check;
}
#Override
public #NonNull View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(mResource, null);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.id = (TextView) convertView.findViewById(R.id.idval);
holder.check = (CheckBox) convertView.findViewById(R.id.choseboxes);
convertView.setTag(holder);
convertView.setTag(R.id.name, holder.name);
convertView.setTag(R.id.idval, holder.id);
convertView.setTag(R.id.choseboxes, holder.check);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.check.setTag(position);
holder.check.setChecked(mCheckStates.get(position, false));
holder.check.setOnCheckedChangeListener(this);
if(ListObject.get(position) instanceof TeamModel.Data)
{
// System.out.println("teh valus are--"+((TeamModel.Data) ListObject.get(position)).getDescription());
holder.name.setText(((TeamModel.Data) ListObject.get(position)).getDescription());
holder.id.setText(Integer.toString(((TeamModel.Data) ListObject.get(position)).getId()));
}
else if(ListObject.get(position) instanceof TeamModel.GroupData)
{
// System.out.println("teh valus are-geroup name--"+((TeamModel.GroupData) ListObject.get(position)).getCceTeamName());
holder.name.setText(((TeamModel.GroupData) ListObject.get(position)).getCceTeamName());
holder.id.setText(Integer.toString(((TeamModel.GroupData) ListObject.get(position)).getId()));
}
// holder.check.setChecked(items.get(position).isSelected());
return convertView;
}
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));
}
}
You should save the checked names in SharedPreferences (for example) and check in your activity's onCreate() the preferences to set previous values.
The activity is created from 0 when you reopen it.
UPDATE:
To pass the checked values:
long[] checkedPositions = new long[]{1, 2, 6, 9, 12}; //Example checked positions
Intent intent = new Intent(context, Activity.class);
intent.putExtra("checked_names", checkedPositions);
context.startActivity(intent);
To check the checkboxes you could use your adapter's method after the adapter is created in the new activity:
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
Or you can create a new constructor for example.

How to add listview items from one activity to listview in another activity in android?

I have a Mainactivity which contain listview and also i have another activity called "WhiteList" which is also containing listview, what i want to add listview items from MainActivity to Listview items of another activity. Please help me do that
code of adapter:-
private LayoutInflater layoutInflater;
private List<AppList> listStorage;
private Context mContext;
int newarr_pos=0;
public AppAdapter(Context context, List<AppList> customizedListView) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
listStorage = customizedListView;
this.mContext = context;
}
#Override
public int getCount() {
return listStorage.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder listViewHolder;
if (convertView == null) {
listViewHolder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.installed_app_list, parent, false);
listViewHolder.textInListView = (TextView) convertView.findViewById(R.id.list_app_name);
listViewHolder.imageInListView = (ImageView) convertView.findViewById(R.id.app_icon);
listViewHolder.switchCompat = (SwitchCompat) convertView.findViewById(R.id.toggleButton);
convertView.setTag(listViewHolder);
} else {
listViewHolder = (ViewHolder) convertView.getTag();
}
listViewHolder.textInListView.setText(listStorage.get(position).getName());
listViewHolder.imageInListView.setImageDrawable(listStorage.get(position).getIcon());
listViewHolder.switchCompat.setTag(position);
listViewHolder.switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
new AlertDialog.Builder(mContext,R.style.AppCompatAlertDialogStyle).setTitle("Warning").setMessage("You want to whiteList this application?").setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//here i am adding items to another arraylist
List<WhiteListModel> res = new ArrayList<WhiteListModel>();
String name = listStorage.get(position).getName();
Drawable icon = listStorage.get(position).getIcon();
String packageName = listStorage.get(position).getPackName();
res.add(new WhiteListModel(name,icon,packageName));
listStorage.remove(position);
notifyDataSetChanged();
listViewHolder.switchCompat.setChecked(false);
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
listViewHolder.switchCompat.setChecked(false);
}
}).show();
}
}
});
return convertView;
}
static class ViewHolder {
SwitchCompat switchCompat;
TextView textInListView;
ImageView imageInListView;
}
}
Assuming you want same list in both activities, while launching another activity you can pass your list to that activity like below:
intent.putExtra("LIST", myList);
Then retrieve list:
ArrayList<TypeOfList> myList = (ArrayList<TypeOfList>) getIntent().getSerializableExtra("LIST");
Finally set the list to your listview:
yourAdapter.setList(myList);
listView.setAdapter(yourAdapter);

checkBox's state changed (which is stored using shared prefrence) automatically when activity changed

i have two activities MainActivity and FilterActivity, in FilterActivity i created a listview with row(Textview,Checkbox) using Custom Adapter.
In the custom Adapter,i use Shared Preference to store the checkbox's state,see below code.
public class filterCustomAdapter extends ArrayAdapter<Application>
{
private final List<Application> list;
Context context;
Editor editor;
ViewHolder viewHolder;
private LayoutInflater inflater;
Set<String> set =new HashSet<String>();
public filterCustomAdapter(Context context, List<Application> list)
{
super(context, R.layout.fil_list_items, list);
this.context = context;
this.list = list;
inflater=LayoutInflater.from(context);
}
public int getCount()
{
return list.size();
}
public Application getItem(int position)
{
return list.get(position);
}
public long getItemId(int position)
{
return position;
}
static class ViewHolder
{
protected TextView text;
protected CheckBox checkbox;
}
#SuppressLint("NewApi")
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
View view = convertView;
final Application item=list.get(position);
view = inflater.inflate(R.layout.fil_list_items, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.fil_txt);
viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check);
view.setTag(viewHolder);
/*else
{
viewHolder=(ViewHolder)convertView.getTag();
}*/
viewHolder.text.setText(list.get(position).getApp_name());
SharedPreferences settings = context.getSharedPreferences("data",Context.MODE_PRIVATE);
boolean Checked = settings.getBoolean(item.getApp_name(),true);
viewHolder.checkbox.setChecked(Checked);
viewHolder.checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#SuppressLint("NewApi")
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if(viewHolder.checkbox.isChecked()==true)
{
SharedPreferences settings = context.getSharedPreferences("data", Context.MODE_PRIVATE);
settings.edit().putBoolean(item.getApp_name(),true).commit();
//set.add(list.get(position).getApp_name());
//settings.edit().putStringSet("selected_app_name",set);
}
else
{
SharedPreferences settings = context.getSharedPreferences("data", Context.MODE_PRIVATE);
settings.edit().putBoolean(item.getApp_name(),false).commit();
//set.remove(list.get(position).getApp_name());
//settings.edit().putStringSet("selected_app_name",set);
}
}
});
return view;
}
}
I commented out some parts which is storing the name of selected item in set which is again stored in shared preference (which is not working either).
My question is, whenever i switch activities the checkboxes are randomly checked and unchecked. i am working with this matter for 4 hours with no luck. pls help. Thank you in advance.
Update : Here is my filterActivity Code:
public class FilterActivity extends Activity
{
ListView listview;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.filter);
listview = (ListView) findViewById(R.id.filter_item_list);
ArrayAdapter<Application> adapter = new filterCustomAdapter(this,getItems());
listview.setAdapter(adapter);
Intent i = getIntent();
String text=i.getStringExtra("activity");
}
private List<Application> getItems()
{
List<Application> list = new ArrayList<Application>();
list.add(get("Message"));
list.add(get("Mail"));
list.add(get("Reminder"));
list.add(get("Event"));
list.add(get("Contact"));
list.add(get("Application"));
list.add(get("Music"));
list.add(get("Video"));
list.add(get("Search Web"));
return list;
}
private Application get(String s)
{
return new Application(s,true,1);
}
}
i am calling this activity from MainActivity whenever a button is clicked.
Please have a look at this code and modify your code as well.
public class MyAdapter extends ArrayAdapter<Model> {
private final List<Model> list;
private final Activity context;
boolean checkAll_flag = false;
boolean checkItem_flag = false;
public MyAdapter(Activity context, List<Model> list) {
super(context, R.layout.row, list);
this.context = context;
this.list = list;
}
static class ViewHolder {
protected TextView text;
protected CheckBox checkbox;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
convertView = inflator.inflate(R.layout.row, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) convertView.findViewById(R.id.label);
viewHolder.checkbox = (CheckBox) convertView.findViewById(R.id.check);
viewHolder.checkbox.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.
list.get(getPosition).setSelected(buttonView.isChecked()); // Set the value of checkbox to maintain its state.
}
});
convertView.setTag(viewHolder);
convertView.setTag(R.id.label, viewHolder.text);
convertView.setTag(R.id.check, viewHolder.checkbox);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.checkbox.setTag(position); // This line is important.
viewHolder.text.setText(list.get(position).getName());
viewHolder.checkbox.setChecked(list.get(position).isSelected());
return convertView;
}
}

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;
}
}

CheckBox gets unchecked on scroll in a custom listview

I know that this question has been asked over and over again but still I've not been a able to find a suggestion that really helps me. The checkbox is unchecked whenever the list is scrolled down. Yes I'm using a boolean array to store the values but this still doesn't fix the problem. Here is my code. Please suggest a solution for this. Thank you.
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
final boolean[] itemChecked=new boolean[30];
LayoutInflater inflater = context.getLayoutInflater();
if(convertView==null)
{
convertView = inflater.inflate(R.layout.custom_list, null);
holder = new ViewHolder();
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.title_text);
holder.txtViewDescription = (TextView) convertView.findViewById(R.id.description_text);
holder.cb=(CheckBox) convertView.findViewById(R.id.cb);
convertView.setTag(holder);
}
else
{
holder=(ViewHolder)convertView.getTag();
}
holder.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
itemChecked[position] = isChecked;
if(itemChecked[position])
{
holder.cb.setChecked(true);
}
else
{
holder.cb.setChecked(false);
}
holder.txtViewTitle.setText(title[position]);
holder.txtViewDescription.setText(description[position]);
holder.cb.setChecked(itemChecked[position]);
holder.txtViewDescription.setFocusable(false);
holder.txtViewTitle.setFocusable(false);
return convertView;
}
}
getView() is called whenever a previously invisible list item needs to be drawn. Since you recreate itemChecked[] each time this method is called you will have the new checkbox unchecked and a different Array for each resulting View. (final in Java does not make that field unique like in C)
Simplest way to solve that is to make itemChecked a classmember and set / restore checkbox state based on that one.
public class MyListAdapter extends ArrayAdapter<Object> {
private final boolean[] mCheckedState;
private final Context mContext;
public MyListAdapter(Context context, int resource, int textViewResourceId, List<Object> objects) {
super(context, resource, textViewResourceId, objects);
mCheckedState = new boolean[objects.size()];
mContext = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// simplified to just a Checkbox
// ViewHolder and OnCheckedChangeListener stuff left out
CheckBox result = (CheckBox)convertView;
if (result == null) {
result = new CheckBox(mContext);
}
result.setChecked(mCheckedState[position]);
return result;
}
}
Here is an example. Read the comments in the getView(...)
of the adapter provided below.
class TaskObject {
private int pid;
private String processName;
private boolean toKill;
///getters/setters
public boolean isToKill() {
return toKill;
}
public void setToKill(boolean toKill) {
this.toKill = toKill;
}
................................
}
class TaskListAdapter extends BaseAdapter {
private static final String TAG = "adapter";
ArrayList<TaskObject> list;
Context context;
public TaskListAdapter(Context context) {
Log.d(TAG, "created new task list adapter");
this.context = context;
if (list == null) {
list = new ArrayList<TaskObject>();
}
}
public void addTask(TaskObject taskObject) {
list.add(taskObject);
}
public void clearTasks() {
list.clear();
Log.d(TAG, "list size:" + list.size());
this.notifyDataSetChanged();
}
public int getCount() {
return list.size();
}
public TaskObject getItem(int position) {
return list.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
RelativeLayout rl = new RelativeLayout(context);
TextView textPid = new TextView(context);
textPid.setText(Integer.toString(getItem(position).getPid()));
TextView textName = new TextView(context);
textName.setText(getItem(position).getProcessName());
/////Here is your and it will set back your checked item after scroll
CheckBox chckKill = new CheckBox(context);
if(getItem(position).isToKill())
{
chckKill.setChecked(true);
}
////////////////////////////////////////////////////////////////////
chckKill.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//is chkIos checked?
if (((CheckBox) v).isChecked()) {
getItem(position).setToKill(true);
}
}
});
chckKill.setTag(getItem(position).getPid());
/////////NOT LAYOUTED USE LAYOUT
rl.addView(chckKill);
rl.addView(textName);
rl.addView(textPid);
return rl;
}
hope it helps abit.
In mycase, I solved this issue as follows :
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
TextView title = null;
ImageView thumbnail = null;
CheckBox checkBox = null;
Content rowData = GridViewActivity.contents.get(position);
if (null == convertView) {
convertView = mInflater.inflate(R.layout.grid_item, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
holder = (ViewHolder) convertView.getTag();
title = holder.getContentTitle();
title.setText(rowData.getTitle());
thumbnail = holder.getThumbnail();
thumbnail.setImageResource(rowData.getIcon());
checkBox = holder.getCheckBox();
checkBox.setTag(position);
checkBox.setChecked(rowData.isCheckBox());
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
int getPosition = (Integer) buttonView.getTag();
GridViewActivity.notifyCheckChanges(getPosition,
buttonView.isChecked());
}
});
return convertView;
}
You should place setChecked() after setOnCheckedChangeListener().

Categories

Resources