how to limit checkbox selection in listview? - android

friends,
i want to limit checkbox selection in android listivew to for example only 3 checkboxes should be selected otherwise it should give error message.
user can select any three checkboxes from the list
any one guide me how to achieve this? here is my adapter
public class AdapterContacts extends BaseAdapter {
private LayoutInflater mInflater;
public Context context;
public static List<myContacts> contacts;
public AdapterContacts(Context context,List<myContacts> list) {
mInflater = LayoutInflater.from(context);
this.context = context;
contacts= list;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_contacts, null);
holder = new ViewHolder();
holder.contactName = (TextView) convertView.findViewById(R.id.contactName);
holder.contactNumber = (TextView) convertView.findViewById(R.id.contactNumber);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
myContacts contact = getItem(position);
holder.checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton checkboxView, boolean isChecked) {
myContacts c = (myContacts) checkboxView.getTag();
c.setSelected(isChecked);
// to put that check of selection limit with error
}
});
holder.checkBox.setTag(contact);
holder.checkBox.setChecked(contact.isSelected());
holder.contactName.setText(contact.getContactName());
holder.contactNumber.setText(contact.getPhoneNumber());
return convertView;
}
#Override
public int getCount() {
return contacts.size();
}
#Override
public myContacts getItem(int position) {
return contacts.get(position);
}
#Override
public long getItemId(int arg0) {
return 0;
}
class ViewHolder {
TextView contactName;
TextView contactNumber;
CheckBox checkBox;
}
}
any help would be appreciated.

finally i solved this issue :) where as globalInc is global variable with default value 0
holder.checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton checkboxView, boolean isChecked)
{
myContacts c = (myContacts) checkboxView.getTag();
if(isChecked)
{
globalInc++;
}
else if(!isChecked)
{
globalInc--;
}
if(globalInc >= 4)// it will allow 3 checkboxes only
{
Toast.makeText(context, "Error = " + globalInc, Toast.LENGTH_LONG).show();
checkboxView.setChecked(false);
globalInc--;
}
else
{
c.setSelected(isChecked);
}
System.out.println(" --------------- "+globalInc);
}
});

i solved the issue "after scroll listview user can also again select more than 3 check boxex" Thanks for you patience
set static int count = 0;
if (isChecked) {
count++;
} else if (!isChecked) {
count--;
}
if (count >= 4) {
buttonView.setChecked(false);
count--;
} else {
int getPosition = (Integer) buttonView.getTag();
contact.get(getPosition).setSelected(buttonView.isChecked());
}
And Most imprtant is that add count=0 in else and viewHolder.chkContact.setTag(position) after else;
if(convertView == null){
}else
{
viewHolder = (ViewHolder) convertView.getTag();
count=0;
}
viewHolder.chkContact.setTag(position);
`

Take a static int count variable and increment it using these condition
holder.checkBox.isChecked() if it is true then increment in the count
then check count>3 then show popup to user
I hope this is Help.

int globalInc = 0;
boolean isCheckGlobal = false;
ArrayList<Integer> checkings = new ArrayList<Integer>();
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
convertView = inflator.inflate(R.layout.list_inner, null);
viewHolder = new ViewHolder();
viewHolder.friendName = (TextView) convertView
.findViewById(R.id.friendName);
viewHolder.checkbox = (CheckBox) convertView
.findViewById(R.id.checkbox);
final MyAdapterSecond objectMyAdapter = new MyAdapterSecond();
viewHolder.checkbox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int getPositionInClick = (Integer) v.getTag();
if (isCheckGlobal == false) {
if (checkings.contains(getPositionInClick)) {
globalInc--;
checkings.remove(checkings.indexOf(getPositionInClick));
} else {
objectMyAdapter.getCheck(false);
}
} else if (isCheckGlobal == true) {
if (checkings.size() < 4) {
globalInc++;
}
}
}
});
viewHolder.checkbox
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
int getPosition = (Integer) buttonView.getTag();
list.get(getPosition).setSelected(
buttonView.isChecked());
callCheck(buttonView, "hi1");
if (checkings.size() > 4 {
Toast.makeText(context, "Error = " + globalInc,
Toast.LENGTH_LONG).show();
objectMyAdapter.setCheck(buttonView);
isCheckGlobal = false;
} else {
buttonView.setSelected(isChecked);
if (isChecked
&& (!checkings.contains(getPosition))) {
checkings.add(getPosition);
}
else if(!isChecked){
if(checkings.contains(getPosition)){
checkings.remove(checkings.indexOf(getPosition));
}
}
isCheckGlobal = true;
}
}
});
convertView.setTag(viewHolder);
convertView.setTag(R.id.friendName, viewHolder.friendName);
convertView.setTag(R.id.checkbox, viewHolder.checkbox);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.checkbox.setTag(position); // This line is important.
viewHolder.friendName.setText(list.get(position).getname());
viewHolder.checkbox.setChecked(list.get(position).isSelected());
return convertView;
}
class MyAdapterSecond {
CompoundButton buttonView;
public void setCheck(CompoundButton buttonView) {
this.buttonView = buttonView;
}
public void getCheck(boolean flag) {
this.buttonView.setChecked(flag);
}
}

Try this:
public class AccountListAdapter extends BaseAdapter {
#SuppressWarnings("unused")
private final static String TAG = AccountListAdapter.class.getSimpleName();
private Context context;
private List<Account> rowItems;
private int selectedItemCounter = 0;
private final int limit;
public AccountListAdapter(Context context, List<Account> items, int limit) {
this.context = context;
this.rowItems = items;
this.limit = limit;
}
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
final Account rowItem = (Account) getItem(position);
convertView = mInflater.inflate(R.layout.account_selection_item, null);
TextView tv = (TextView) convertView.findViewById(R.id.textView);
ToggleButton tb = (ToggleButton) convertView
.findViewById(R.id.toggleButton);
tb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked && !rowItem.isSelected()) {
if (selectedItemCounter >= limit) {
Toast.makeText(context,
"can't be more" + selectedItemCounter,
Toast.LENGTH_SHORT).show();
buttonView.setChecked(false);
return;
}
rowItem.setSelected(true);
selectedItemCounter++;
} else if (!isChecked && rowItem.isSelected()) {
rowItem.setSelected(false);
selectedItemCounter--;
}
}
});
tv.setText(rowItem.getDevId());
tb.setChecked(rowItem.isSelected());
return convertView;
}
#Override
public int getCount() {
return rowItems.size();
}
#Override
public Object getItem(int position) {
return rowItems.get(position);
}
#Override
public long getItemId(int position) {
return rowItems.indexOf(getItem(position));
}
}
tried to improve my code with ViewHolder pattern but failed.
if anyone have better idea, please let me know.

Related

check box unchecked issue when i scroll the custom listview android

listview row having multiple checkboxex, when i checked the checkboxex then if i scroll the listview, its automatically unchecked the checkboxes. how can fix this issue. here is my getView method
public View getView(final int position, View convertView, ViewGroup parent) {
final QuestionRadioHolder questionRadioHolder;
final QuestionCheckboxHolder questionCheckboxHolder;
final Model rowItem = getItem(position);
final int type = getItemViewType(position);
if (type == TYPE1) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.radio_layout, parent, false);
questionRadioHolder = new QuestionRadioHolder();
questionRadioHolder.txtQuestion = (TextView) convertView.findViewById(R.id.txtQue);
questionRadioHolder.rg = (RadioGroup) convertView.findViewById(R.id.rg);
Typeface face = Typeface.createFromAsset(getContext().getAssets(), "fonts/Raleway-SemiBold.ttf");
questionRadioHolder.txtQuestion.setTypeface(face);
convertView.setTag(questionRadioHolder);
} else {
questionRadioHolder = (QuestionRadioHolder) convertView.getTag();
}
List<String> arrayList = rowItem.getArrayList();
questionRadioHolder.txtQuestion.setText(rowItem.getQuestionText());
questionRadioHolder.rg.removeAllViews();
questionRadioHolder.rg.clearCheck();
for (int i = 0; i < arrayList.size(); i++) {
RadioButton radioButton = new RadioButton(getContext());
radioButton.setId(i);
radioButton.setTextSize(12);
radioButton.setText(arrayList.get(i));
radioButton.setTypeface(face1);
questionRadioHolder.rg.addView(radioButton);
}
// questionRadioHolder.rg.removeAllViews();
questionRadioHolder.rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup rg, int checkedId) {
for (int i = 0; i < rg.getChildCount(); i++) {
RadioButton btn = (RadioButton) rg.getChildAt(i);
ArrayList<String> list = new ArrayList<String>();
if (btn.getId() == checkedId) {
String text = btn.getText().toString();
int id = mList.get(position).getQuid();
System.out.println(position + " position 2");
map.put(id, text);
list.add(0, text);
aMap1.put(id, list);
Log.d("radio", text);
Log.d("Queid:", "" + id);
return;
}
}
}
});
} else if (type == TYPE2) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.checkbox_layout, parent, false);
questionCheckboxHolder = new QuestionCheckboxHolder();
questionCheckboxHolder.txtQuestionChk = (TextView) convertView.findViewById(R.id.chkQues);
questionCheckboxHolder.relativeLayout = (LinearLayout) convertView.findViewById(R.id.chkrl2);
Typeface face = Typeface.createFromAsset(getContext().getAssets(), "fonts/Raleway-SemiBold.ttf");
face1 = Typeface.createFromAsset(getContext().getAssets(), "fonts/Raleway-Regular.ttf");
questionCheckboxHolder.txtQuestionChk.setTypeface(face);
convertView.setTag(questionCheckboxHolder);
} else {
questionCheckboxHolder = (QuestionCheckboxHolder) convertView.getTag();
}
List<String> arrayList = rowItem.getArrayList();
questionCheckboxHolder.txtQuestionChk.setText(rowItem.getQuestionText());
questionCheckboxHolder.relativeLayout.removeAllViews();
for (int i = 0; i < arrayList.size(); i++) {
checkBox = new CheckBox(getContext());
checkBox.setId(i);
checkBox.setMinHeight(30);
checkBox.setMinimumWidth(30);
checkBox.setText(arrayList.get(i));
checkBox.setTypeface(face1);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int position = (Integer) buttonView.getTag();
ArrayList<String> arraylist2 = new ArrayList<String>();
ArrayList<String> list = new ArrayList<String>();
int id = mList.get(position).getQuid();
arraylist2 = aMap1.get(id);
System.out.println(arraylist2);
if (arraylist2 == null) {
arraylist2 = list;
}
if (buttonView.isChecked()) {
arraylist2.add(buttonView.getText().toString());
aMap1.put(id, arraylist2);
} else {
arraylist2.remove(buttonView.getText().toString());
aMap1.put(id, arraylist2);
}
System.out.println(aMap1.get(id));
}
});
questionCheckboxHolder.relativeLayout.addView(checkBox);
}
}
return convertView;
}
If i scroll the listview, its automatically unchecked the checkbox, how can checked the checkbox.
Try this way this worked for me
public class CustomAdapter extends BaseAdapter {
private final LayoutInflater inflater;
private final Context context;
private List<ModelCls> listData;
public CustomAdapter(Context mainActivity, List<ModelCls> listData) {
context = mainActivity;
this.listData = listData;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.list_item_poojaselection, null);
holder.tv = (TextView) convertView.findViewById(R.id.list_item_poojaname);
holder.checks = (CheckBox) convertView.findViewById(R.id.list_item_poojacheck);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
holder.checks.setOnCheckedChangeListener(null);
holder.checks.setFocusable(false);
if (listData.get(position).isselected) {
holder.checks.setChecked(true);
} else {
holder.checks.setChecked(false);
}
holder.checks.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton cb, boolean b) {
if (checkMaxLimit()) {
if (listData.get(position).isselected && b) {
holder.checks.setChecked(false);
listData.get(position).isselected = false;
} else {
holder.checks.setChecked(false);
listData.get(position).isselected = false;
Toast.makeText(context, "Max limit reached", Toast.LENGTH_SHORT).show();
}
} else {
if (b) {
listData.get(position).isselected = true;
} else {
listData.get(position).isselected = false;
}
}
}
});
holder.tv.setText(listData.get(position).getLISTING_NAME());
return convertView;
}
public boolean checkMaxLimit() {
int countermax = 0;
for(ModelCls item : listData){
if(item.isselected){
countermax++;
}
}
return countermax >= 5;
}
public class ViewHolder {
TextView tv;
public CheckBox checks;
}
}
and if you want to recyclerview try this
http://android-pratap.blogspot.in/2015/01/recyclerview-with-checkbox-example.html
Save your check list in ArrayList<Boolean>, and load it in getView():
ArrayList<Boolean> listCheck;
public YourAdapter(Context context, int resource, ArrayList<T> list) {
super(context, resource, list);
listCheck = new ArrayList<Boolean>;
for (int i = 0; i < list.size(); i++) {
listCheck.add(false); // init listCheck
}
}
public View getView(final int position, View convertView, ViewGroup parent) {
yourCheckBox.setChecked(listCheck.get(position)); // set checkbox
yourCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
listCheck.set(position, isChecked); // update listChecked
}
}
}
If you checked on checkbox, you can save it into a HashMap(key:position, value:true/false), and in method getView() you can distinguish which is checked or unchecked, then make the checkbox show its state.
Try Using a model class or array to keep the values of checkbox and update it on onclick if that checkbox may solve your issue I think.
holder.checkBox.setChecked(mCheckList.get(position));
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCheckList.set(position, !mCheckList.get(position));
notifyDataSetChanged();
}
});

duplicate selection of Check boxes in android listview

Am using check boxes in listview and am able to get the selected values also but my problem is when select the first position checkbox, automatically selecting 7th positioned checkbox. what will be the problem and please suggest me how to resolve this problem.
public class TransactionAdapter extends BaseAdapter {
LayoutInflater inflator;
String veh_reg_no;
String fuel_qty, total_amt;
public TransactionAdapter(Context context) {
inflator = getLayoutInflater();
}
#Override
public int getCount() {
if (pso_transaction_list.size() != 0)
return pso_transaction_list.size();
return 0;
}
#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 holder;
if(convertView==null) {
convertView = inflator.inflate(R.layout.pso_transation_layout, parent, false);
holder=new Viewholder();
holder.vT_tl_regnumber = (TextView) convertView.findViewById(R.id.vT_psotl_regnumber);
holder.vT_tl_drivername = (TextView) convertView.findViewById(R.id.vT_psotl_drivername);
holder.vT_tl_quantity = (TextView) convertView.findViewById(R.id.vT_psotl_quantity);
holder.vT_tl_totalCost = (TextView) convertView.findViewById(R.id.vT_psotl_totalCost);
holder.vT_psotl_payment = (TextView) convertView.findViewById(R.id.vT_psotl_payment);
holder.vI_psotl_statusimg = (ImageView) convertView.findViewById(R.id.vI_psotl_statusimg);
holder.vI_pha_Next = (ImageView) convertView.findViewById(R.id.vI_pha_Next);
holder.vI_pha_select = (CheckBox) convertView.findViewById(R.id.vI_pha_select);
holder.vT_psotl_unit = (TextView) convertView.findViewById(R.id.vT_psotl_unit);
holder.vT_pha_rsr = (TextView) convertView.findViewById(R.id.vT_pha_rsr);
holder.vL_psotl_nextlayout = (LinearLayout) convertView.findViewById(R.id.vL_psotl_nextlayout);
holder.vL_psotl_checkboxlayout = (LinearLayout) convertView.findViewById(R.id.vL_psotl_checkboxlayout);
convertView.setTag(holder);
}else{
holder = (Viewholder) convertView.getTag();
holder.vI_pha_select.setOnCheckedChangeListener(null);
}
if (pso_transaction_list.get(position).getPaymentMode().getId() == 1 && pso_transaction_list.get(position).getWFStatus() == 7) {
String pmt_status = "C/A | RCVD ";
holder.vT_psotl_payment.setText(pmt_status);
} else if (pso_transaction_list.get(position).getPaymentMode().getId() == 1) {
holder.vT_psotl_payment.setText("C/A");
} else {
holder.vT_psotl_payment.setText("P/G");
}
if (pso_transaction_list.get(position).getFuelStations().getCountry() != null) {
String[] currency = Getlocationaddress_by_address.currency(pso_transaction_list.get(position).getFuelStations().getCountry(), PsomytransactionlistActivity.this);
holder.vT_pha_rsr.setText(" " + currency[0] + " ");
holder.vT_psotl_unit.setText(" " + currency[1]);
}
holder.vI_pha_select.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked{
if (isChecked) {
selected_list_payment.add(pso_transaction_list.get(position).getPaymentMode().getId() + "");
selected_list.add(pso_transaction_list.get(position).getId() + "");
selecteddetails.add(pso_transaction_list.get(position).getVehicleNo());
payment_status.add(pso_transaction_list.get(position).getWFStatus() + "");
} else {
selected_list.remove(pso_transaction_list.get(position).getId() + "");
selected_list_payment.remove(pso_transaction_list.get(position).getPaymentMode().getId() + "");
selecteddetails.remove(pso_transaction_list.get(position).getVehicleNo());
payment_status.remove(pso_transaction_list.get(position).getWFStatus() + "");
}
}
});
veh_reg_no = pso_transaction_list.get(position).getVehicleNo();
holder.vT_tl_regnumber.setText(veh_reg_no);
holder.vT_tl_drivername.setText(pso_transaction_list.get(position).getDriver().getName());
fuel_qty = " " + pso_transaction_list.get(position).getQuantity() + "";
holder.vT_tl_quantity.setText(fuel_qty);
total_amt = pso_transaction_list.get(position).getTotalPrice() + "";
holder.vT_tl_totalCost.setText(total_amt);
holder.vL_psotl_nextlayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent trans_intent = new Intent(PsomytransactionlistActivity.this, Psotransactiondetails.class);
trans_intent.putExtra("trans_details_position", position);
startActivity(trans_intent);
}
});
return convertView;
}
}
public static class Viewholder{
public TextView vT_tl_regnumber, vT_tl_drivername, vT_tl_quantity, vT_tl_totalCost, vT_psotl_payment, vT_psotl_unit, vT_pha_rsr;
public ImageView vI_psotl_statusimg, vI_pha_Next;
public LinearLayout vL_psotl_nextlayout, vL_psotl_checkboxlayout;
public CheckBox vI_pha_select;
}
Try this way. this worked for me
public class CustomAdapter extends BaseAdapter {
private final LayoutInflater inflater;
private final Context context;
private List<ModelPooja> listData;
public CustomAdapter(Context mainActivity, List<ModelPooja> listData) {
context = mainActivity;
this.listData = listData;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.list_item_poojaselection, null);
holder.tv = (TextView) convertView.findViewById(R.id.list_item_poojaname);
holder.checks = (CheckBox) convertView.findViewById(R.id.list_item_poojacheck);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
holder.checks.setOnCheckedChangeListener(null);
holder.checks.setFocusable(false);
if (listData.get(position).isselected) {
holder.checks.setChecked(true);
} else {
holder.checks.setChecked(false);
}
holder.checks.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton cb, boolean b) {
if (checkMaxLimit()) {
if (listData.get(position).isselected && b) {
holder.checks.setChecked(false);
listData.get(position).isselected = false;
} else {
holder.checks.setChecked(false);
listData.get(position).isselected = false;
Toast.makeText(context, "Max limit reached", Toast.LENGTH_SHORT).show();
}
} else {
if (b) {
listData.get(position).isselected = true;
} else {
listData.get(position).isselected = false;
}
}
}
});
holder.tv.setText(listData.get(position).getPOOJA_LISTING_NAME());
return convertView;
}
public boolean checkMaxLimit() {
int countermax = 0;
for(ModelPooja item : listData){
if(item.isselected){
countermax++;
}
}
return countermax >= 5;
}
public class ViewHolder {
TextView tv;
public CheckBox checks;
}
}
For Recyclerview try this way
http://android-pratap.blogspot.in/2015/01/recyclerview-with-checkbox-example.html
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
Add two functions into your "Adapter" class
Note: If you use RecycleView, just add getItemViewType(int position).

listView checkbox scrolling bug

I have a problem with a listView consisting of check-boxes. When I scroll some items get selected automatically.
This is my code for the getView method in my custom adapter:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
convertView = inflater.inflate(R.layout.prerequisite_course, parent, false);
holder = new ViewHolder();
holder.name = (CheckBox) convertView.findViewById(R.id.course_checkbox);
convertView.setTag(holder);
holder.name.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v ;
Course course = (Course) cb.getTag();
if (cb.isChecked())
checkBoxChecked(cb, course);
else
checkBoxNotChecked(cb, course);
}
});
}
else {
holder = (ViewHolder) convertView.getTag();
}
Course course = coursesDataManager.getCourseInPosition(position);
String currentId = COURSES_SUBJECT + " " + course.getId();
holder.name.setText(currentId);
holder.name.setTag(course);
// for the clear button:
if (!holder.name.isChecked()) {
checkBoxNotChecked(holder.name, (Course) holder.name.getTag());
}
return convertView;
}
private void checkBoxChecked(CheckBox cb, Course add) {
cb.setBackgroundColor(Color.rgb(1, 67, 121));
cb.setTextColor(Color.WHITE);
myCoursesManager.addPrerequisite(add);
}
private void checkBoxNotChecked(CheckBox cb, Course remove) {
cb.setBackgroundColor(Color.WHITE);
cb.setTextColor(Color.BLACK);
myCoursesManager.removePrerequisite(remove);
}
Also, criticism of the code would be welcomed as I'm new to android development. Thank you.
You need to maintain boolean array for checkbox,try this way this worked for me
public class CustomAdapter extends BaseAdapter {
private final LayoutInflater inflater;
private final Context context;
private List<ModelPooja> listData;
public CustomAdapter(Context mainActivity, List<ModelPooja> listData) {
context = mainActivity;
this.listData = listData;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.list_item_poojaselection, null);
holder.tv = (TextView) convertView.findViewById(R.id.list_item_poojaname);
holder.checks = (CheckBox) convertView.findViewById(R.id.list_item_poojacheck);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
holder.checks.setOnCheckedChangeListener(null);
holder.checks.setFocusable(false);
if (listData.get(position).isselected) {
holder.checks.setChecked(true);
} else {
holder.checks.setChecked(false);
}
holder.checks.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton cb, boolean b) {
if (checkMaxLimit()) {
if (listData.get(position).isselected && b) {
holder.checks.setChecked(false);
listData.get(position).isselected = false;
} else {
holder.checks.setChecked(false);
listData.get(position).isselected = false;
Toast.makeText(context, "Max limit reached", Toast.LENGTH_SHORT).show();
}
} else {
if (b) {
listData.get(position).isselected = true;
} else {
listData.get(position).isselected = false;
}
}
}
});
holder.tv.setText(listData.get(position).getPOOJA_LISTING_NAME());
return convertView;
}
public boolean checkMaxLimit() {
int countermax = 0;
for(ModelPooja item : listData){
if(item.isselected){
countermax++;
}
}
return countermax >= 5;
}
public class ViewHolder {
TextView tv;
public CheckBox checks;
}
}
Create a Model Class for saving the checkBox status for the list items.
public class ModelClass
{
int position=null;
String item=null;
boolean selected=false;
public ModelClass(int position,String item, boolean selected) {
super();
this.position=position;
this.item=item;
this.selected = selected;
}
}
Then in your Adapter Class
private ArrayList<ModelClass> arl;
Inside your getView()
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
arl.get(position).selected=isChecked;
}
});
holder.checkBox.setChecked(arl.get(position).selected);
And now no matter how much you scroll your checkBoxes state will be consistent(Trust me, I have used this code in my Project).

Onscroll selected checkbox getting unchecked using listiview

In my application i added checkbox with ListView,and i also gave limitation for checkbox,user can not select more than 5 checkbox,but the issue is on scroll my selected checkbox get unchecked following is my snippet code,can any one help me with this
public class CustomAdapter extends BaseAdapter {
private LayoutInflater inflater = null;
Context context;
String rup = "\u20B9";
private ArrayList<ModelPooja> listData;
boolean checked[];
public CustomAdapterPooja(Context mainActivity, ArrayList<ModelPooja> listData) {
// TODO Auto-generated constructor stub
context = mainActivity;
this.listData = listData;
inflater = (LayoutInflater) context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
checked = new boolean[listData.size()];
for (int i = 0; i < checked.length; i++) {
checked[i] = listData.get(i).isselected;
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listData.size();
}
#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 position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.list_item_poojaselection, null);
holder.tv = (TextView) convertView.findViewById(R.id.list_item_poojaname);
holder.serviceprice = (TextView) convertView.findViewById(R.id.list_item_poojaprice);
holder.dayss = (TextView) convertView.findViewById(R.id.list_item_poojadays);
holder.txtseledates = (TextView) convertView.findViewById(R.id.selecteddatess);
holder.checks = (CheckBox) convertView.findViewById(R.id.list_item_poojacheck);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
holder.checks.setOnCheckedChangeListener(null);
holder.checks.setFocusable(false);
holder.checks.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton cb, boolean b) {
if (checkMaxLimit()) {
if (listData.get(position).isselected && b) {
holder.checks.setChecked(false);
listData.get(position).isselected = false;
} else {
holder.checks.setChecked(false);
listData.get(position).isselected = false;
Toast.makeText(context, "Max limit reached", Toast.LENGTH_SHORT).show();
}
} else {
if (b) {
listData.get(position).isselected = true;
} else {
listData.get(position).isselected = false;
}
}
}
});
if (listData.get(position).isselected()) {
holder.checks.setChecked(true);
} else {
holder.checks.setChecked(false);
}
holder.tv.setText(listData.get(position).getPOOJA_LISTING_NAME());
holder.dayss.setText(listData.get(position).getPOOJA_LISTING_DAYS());
holder.serviceprice.setText(rup + listData.get(position).getPOOJA_LISTING_AMOUNT());
return convertView;
}
public boolean checkMaxLimit() {
int countermax = 0;
for (int i = 0; i < checked.length; i++) {
checked[i] = false;
checked[i] = listData.get(i).isselected();
if (listData.get(i).isselected()) {
countermax++;
}
}
return countermax >= 5 ? true : false;
}
public class ViewHolder {
TextView tv;
TextView serviceprice;
public CheckBox checks;
public TextView dayss;
public TextView txtseledates;
}
}
Problem is in your getView() method. You set OnCheckedChangeListener and after that you set checkbox to true or false which fires callback in that listener. You should set checkbox check state first and after that set OnCheckedChangeListener.
Also, that boolean checked[] field is useless, so I simplified your code a little:
public class CustomAdapter extends BaseAdapter {
private final LayoutInflater inflater;
private final Context context;
private List<ModelPooja> listData;
public CustomAdapter(Context mainActivity, List<ModelPooja> listData) {
context = mainActivity;
this.listData = listData;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.list_item_poojaselection, null);
holder.tv = (TextView) convertView.findViewById(R.id.list_item_poojaname);
holder.checks = (CheckBox) convertView.findViewById(R.id.list_item_poojacheck);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
holder.checks.setOnCheckedChangeListener(null);
holder.checks.setFocusable(false);
if (listData.get(position).isselected) {
holder.checks.setChecked(true);
} else {
holder.checks.setChecked(false);
}
holder.checks.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton cb, boolean b) {
if (checkMaxLimit()) {
if (listData.get(position).isselected && b) {
holder.checks.setChecked(false);
listData.get(position).isselected = false;
} else {
holder.checks.setChecked(false);
listData.get(position).isselected = false;
Toast.makeText(context, "Max limit reached", Toast.LENGTH_SHORT).show();
}
} else {
if (b) {
listData.get(position).isselected = true;
} else {
listData.get(position).isselected = false;
}
}
}
});
holder.tv.setText(listData.get(position).getPOOJA_LISTING_NAME());
return convertView;
}
public boolean checkMaxLimit() {
int countermax = 0;
for(ModelPooja item : listData){
if(item.isselected){
countermax++;
}
}
return countermax >= 5;
}
public class ViewHolder {
TextView tv;
public CheckBox checks;
}
}
Make a Boolean array initially with false value in adapter.If user checks the array make array's position true. On uncheck make it false. Always set the checkbox value from that boolean array.
This is because when you scroll your listview from upper or lower side of phone, all items of listview are regenerated and they are set to default value.
To avoid this make a model class which holds the current value of checkbox(true or false) and set the value of checkbox in adapter by calling getter method from that model instance.
For example:
model.java
public class AddressModel {
private boolean isChecked;
private String address;
private int alAddressDelete;
public AddressModel(){
}
public AddressModel(boolean isChecked, String address, int alAddressDelete) {
this.isChecked = isChecked;
this.address = address;
this.alAddressDelete = alAddressDelete;
}
public boolean getIsChecked() {
return isChecked;
}
public void setIsChecked(boolean isChecked) {
this.isChecked = isChecked;
}
}
In your Adapter class set the value of checkbox by calling setIsChecked(boolean isChecked) in the setOnCheckedChangeListener().
call getIsChecked() where you are setting value of your checkboxes.
Call setOnCheckedChangeListener() first, then call setChecked(), otherwise the setChecked() will trigger the previous ViewHolder object's setOnCheckedChangeListener().

Android : Check-box issue in Grid-View

I'm trying to delete multiple selected images from Grid View.Images are deleted proper way but check box was appear as it is grid-view on Button click event.Can someone help me for solve this issue.Thanks in advance.
Here is my Code deletion
class GridView_Adapter extends BaseAdapter {
private LayoutInflater mInflater;
SparseBooleanArray mSparseBooleanArray;
public GridView_Adapter() {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mSparseBooleanArray = new SparseBooleanArray();
}
public ArrayList<String> getCheckedItems() {
ArrayList<String> mTempArry = new ArrayList<String>();
for(int i=0;i<fileName.size();i++) {
if(mSparseBooleanArray.get(i)) {
mTempArry.add(fileName.get(i));
}}
return mTempArry;
}
public int getCount() {
return fileName.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
if (convertView == null)
{
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.add_post_grid_item_layout, parent , false);
holder.image = (ImageView) convertView.findViewById(R.id.image);
holder.checkbox = (CheckBox) convertView.findViewById(R.id.itemCheckBox);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
Bitmap myBitmap = BitmapFactory.decodeFile(fileName.get(position));
holder.image.setImageBitmap(myBitmap);
final int pos = position;
holder.checkbox.setTag(position);
holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
mSparseBooleanArray.put((Integer) buttonView.getTag(), isChecked);
int pos = (Integer) buttonView.getTag();
if (!buttonView.isChecked())
{
picsName.remove((String) fileName.get(pos));
}
else if(buttonView.isChecked())
{
if (!picsName.contains((String) fileName.get(pos)))
{
picsName.add((String) fileName.get(pos));
}
}
notifyDataSetChanged();
}
});
return convertView;
}
class ViewHolder
{
ImageView image;
CheckBox checkbox;
int id;
}
}
And here is delete button
imgDeleteImagesFromGallery = (ImageView) findViewById(R.id.imgDeleteImage);
if(gridAdapter.getCheckedItems()!= null )
{
selectedItems = gridAdapter.getCheckedItems();
if(selectedItems != null )
{
imgDeleteImagesFromGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if(selectedItems.size() > 0)
{
Toast.makeText(AddPost.this, "Total photos selected: "+selectedItems.size(), Toast.LENGTH_SHORT).show();
Log.e(AddPost.class.getSimpleName(), "Selected Items: " + selectedItems.toString());
Iterator it = picsName.iterator();
while (it.hasNext())
{
strFilePath = it.next().toString();
Log.e("strFilePath ", " strFilePath = " + strFilePath);
File file = new File(strFilePath);
if (file.exists())
{
boolean result = file.delete();
Log.e("File deleted ", " From classnkk_images = " + result);
}
}
gridAdapter.notifyDataSetChanged();
int countImg = gridAdapter.getCount();
textTotalImages.setText(Integer.toString(countImg));
}
}
});
}
}

Categories

Resources