I have a Custom adapter class, as follows.When I select one checkbox,other checkboxes also gets selected after 7-8 rows. Even if setonclicklisterner is not implement, checkboxes behaves the same. I need a proper solution. I searched a lot but not getting the solution.
How can I stop avoiding the multiple selection of checkboxes?
public class CustomAdapter extends ArrayAdapter<Custom>{
private ArrayList<Custom> entries;
private Activity activity;
private Context context;
private qrusers qrusers;
private String[] udis;
ArrayList<String> userid= new ArrayList<String>();
boolean[] checkBoxState;
LayoutInflater vi;
public CustomAdapter(Context context, ArrayList<Custom> entries,String []udis) {
super(context,0,entries);
this.entries = entries;
this.context= context;
this.udis=udis;
checkBoxState=new boolean[entries.size()];
this.qrusers =(qrusers) context;
vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public static class ViewHolder{
public TextView item1;
public TextView item2;
public CheckBox chek;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if (v == null) {
v = vi.inflate(R.layout.checkboxlist, null);
holder = new ViewHolder();
holder.item1 = (TextView) v.findViewById(R.id.contactname);
holder.item2 = (TextView) v.findViewById(R.id.companyname);
holder.chek=(CheckBox)v.findViewById(R.id.checboxlist);
holder.chek.setTag(udis[position]);
v.setTag(holder);
/* holder.chek.setOnCheckedChangeListener(new OnCheckedChangeListener() {
private String s;
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
checkBoxState[position]=true;
// isChecked=true;
s=(String)buttonView.getTag();
Log.e("IDDDDDDDD", s);
userid.add(s);
Log.e("ADDED ID", userid.toString());
}
else{
checkBoxState[position]=false;
s=(String)buttonView.getTag();
userid.remove(s);
Log.e("Removed ID", userid.toString());
}
}
});*/
holder.chek.setOnClickListener(new OnClickListener() {
private String s;
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()){
checkBoxState[position]=true;
// isChecked=true;
s=(String)v.getTag();
Log.e("IDDDDDDDD", s);
userid.add(s);
Log.e("ADDED ID", userid.toString());
}
else{
checkBoxState[position]=false;
s=(String)v.getTag();
userid.remove(s);
Log.e("Removed ID", userid.toString());
}
}
});
holder.chek.setChecked(checkBoxState[position]);
CheckBox result = (CheckBox)convertView;
if (result == null) {
result = new CheckBox(context);
}}
else
holder=(ViewHolder)v.getTag();
final Custom custom = entries.get(position);
if (custom != null) {
holder.item1.setText(custom.getcustomBig());
holder.item2.setText(custom.getcustomSmall());
}
return v;
}
public ArrayList<String> getUserid() {
return userid;
}
public void setUserid(ArrayList<String> userid) {
this.userid = userid;
}
}
use this code for base adapter.
public class CollageView extends BaseAdapter {
Context context;
ArrayList<String> image_arrylist = new ArrayList<String>();
File file;
Bitmap bm;
LayoutInflater inflater;
ImageView imageview;
ViewHolder holder = null;
int position;
public CollageView(Context c, ArrayList<String> array_list) {
context = c;
imageview = new ImageView(c);
image_arrylist = array_list;
inflater = LayoutInflater.from(context);
System.out.println("Size-&&7" + image_arrylist.size());
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return image_arrylist.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
View v = convertView;
if (v == null) {
v = inflater.inflate(R.layout.collage_image_row, null);
holder = new ViewHolder();
holder.image = (ImageView) v
.findViewById(R.id.imageView_collage);
holder.checkbox = (CheckBox) v
.findViewById(R.id.itemCheckBox_collage_image);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.checkbox.setId(position);
holder.image.setId(position);
if (CollageViewActivity.checkbox_boolean == true) {
holder.checkbox.setVisibility(View.VISIBLE);
}
System.out.println("aname" + aname);
holder.checkbox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
System.out.println("click-1");
// TODO Auto-generated method stub
CheckBox cb = (CheckBox) v;
int id = cb.getId();
if (thumbnailsselection[id]) {
cb.setChecked(false);
thumbnailsselection[id] = false;
} else {
cb.setChecked(true);
thumbnailsselection[id] = true;
}
}
});
holder.checkbox.setChecked(thumbnailsselection[position]);
holder.id = position;
System.out.println("set image..." + image_arrylist.get(position));
file = new File(image_arrylist.get(position));
String ext = file.toString();
if (checkVideo(file)) {
System.out.println("video exist " + file.exists());
holder.image.setScaleType(ImageView.ScaleType.CENTER);
aq.id(holder.image).image(
getVideoThumnail(image_arrylist.get(position)));
} else {
System.out.println("file exist " + file.exists());
holder.image.setScaleType(ImageView.ScaleType.CENTER);
aq.id(holder.image).image(file, 300);
}
holder.image.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("labelorcollage"
+ GeneralClass.lableorcollage
+ image_arrylist.size());
GeneralClass.checkfullimage = true;
// gridview.setVisibility(View.GONE);
playout_image.setVisibility(View.VISIBLE);
playout_grid.setVisibility(View.GONE);
}
});
return v;
}
public class ViewHolder {
TextView imageTitle;
ImageView image;
RelativeLayout layout;
CheckBox checkbox;
int id;
}
}
//try to replace this peace of code
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if (v == null) {
v = vi.inflate(R.layout.checkboxlist, null);
holder = new ViewHolder();
holder.item1 = (TextView) v.findViewById(R.id.contactname);
holder.item2 = (TextView) v.findViewById(R.id.companyname);
holder.chek=(CheckBox)v.findViewById(R.id.checboxlist);
v.setTag(holder);
}else{
holder=(ViewHolder)v.getTag();
}
holder.chek.setChecked(checkBoxState[position]);
holder.chek.setTag(position);
holder.chek.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
checkBoxState[(Integer)((CheckBox)compoundButton).getTag()]=b;
if(b){
userid.add(udis[(Integer)((CheckBox)compoundButton).getTag()]);
}else{
userid.remove(udis[(Integer)((CheckBox)compoundButton).getTag()]);
}
}
});
final Custom custom = entries.get(position);
if (custom != null) {
holder.item1.setText(custom.getcustomBig());
holder.item2.setText(custom.getcustomSmall());
}
return v;
}
check out this link: http://sunil-android.blogspot.in/2013/04/android-listview-checkbox-example.html and follow steps he took it might help you! it helped me too to have checked only the checkbox i selected.
Related
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).
I am newbie to android and working on a listView which is having checkboxes in items,When i check any item other item also cehcked automaticaly,Can any one help me how to solve it my adapter is as below,
public class ServiceAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> contArray;
ArrayList<Boolean> checked;
private Context mContext;
String resnID, reson;
Intent i;
public ServiceAdapter(Context paramContext, ArrayList<HashMap<String, String>> contList) {
this.mContext = paramContext;
this.contArray = contList;
checked = new ArrayList<>();
}
public int getCount() {
return this.contArray.size();
}
public Object getItem(int paramInt) {
return Integer.valueOf(paramInt);
}
public long getItemId(int paramInt) {
return paramInt;
}
public View getView(final int paramInt, View paramView,
ViewGroup paramViewGroup) {
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext
.getSystemService("layout_inflater");
Viewholder localViewholder = null;
Const.selectedIDs.clear();
if (paramView == null) {
paramView = localLayoutInflater.inflate(
R.layout.raw_single_contact, paramViewGroup, false);
localViewholder = new Viewholder();
localViewholder.tv_name = ((TextView) paramView
.findViewById(R.id.tv_name));
localViewholder.chk_id = ((CheckBox) paramView
.findViewById(R.id.chk_id));
paramView.setTag(localViewholder);
paramView.setTag(R.id.chk_id, localViewholder.chk_id );
} else {
localViewholder = (Viewholder) paramView.getTag();
}
localViewholder.tv_name.setText(contArray.get(paramInt).get("serviceText"));
localViewholder.chk_id.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
try {
if (isChecked) {
Const.selectedIDs.add(contArray.get(paramInt));
Const.serviceArrayList.get(paramInt).put("flag", "1");
} else {
Const.selectedIDs.remove(contArray.get(paramInt));
Const.serviceArrayList.get(paramInt).put("flag", "0");
}
}catch (Exception e){
e.printStackTrace();
}
}
});
return paramView;
}
static class Viewholder {
TextView tv_name;
CheckBox chk_id;
}
}
Check this code, this will help you,
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.country_info, null);
holder = new ViewHolder();
holder.code = (TextView) convertView.findViewById(R.id.code);
holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
holder.name.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v ;
Country country = (Country) cb.getTag();
Toast.makeText(getApplicationContext(),
"Clicked on Checkbox: " + cb.getText() +
" is " + cb.isChecked(),
Toast.LENGTH_LONG).show();
country.setSelected(cb.isChecked());
}
});
}
else {
holder = (ViewHolder) convertView.getTag();
}
Country country = countryList.get(position);
holder.code.setText(" (" + country.getCode() + ")");
holder.name.setText(country.getName());
holder.name.setChecked(country.isSelected());
holder.name.setTag(country);
return convertView;
}
}
private void checkButtonClick() {
Button myButton = (Button) findViewById(R.id.findSelected);
myButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
StringBuffer responseText = new StringBuffer();
responseText.append("The following were selected...\n");
ArrayList<Country> countryList = dataAdapter.countryList;
for(int i=0;i<countryList.size();i++){
Country country = countryList.get(i);
if(country.isSelected()){
responseText.append("\n" + country.getName());
}
}
Toast.makeText(getApplicationContext(),
responseText, Toast.LENGTH_LONG).show();
}
});
}
Here you go read comments which i added.
public class ServiceAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> contArray;
ArrayList<Boolean> checked;
private Context mContext;
String resnID, reson;
Intent i;
public ServiceAdapter(Context paramContext, ArrayList<HashMap<String, String>> contList) {
this.mContext = paramContext;
this.contArray = contList;
//update code there make list of same size as contList
checked = new ArrayList<>(contList.size());
//On start all are unchecked
Collections.fill(checked, Boolean.FALSE);
}
public int getCount() {
return this.contArray.size();
}
public Object getItem(int paramInt) {
return Integer.valueOf(paramInt);
}
public long getItemId(int paramInt) {
return paramInt;
}
public View getView(final int paramInt, View paramView,
ViewGroup paramViewGroup) {
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext
.getSystemService("layout_inflater");
Viewholder localViewholder = null;
Const.selectedIDs.clear();
if (paramView == null) {
paramView = localLayoutInflater.inflate(
R.layout.raw_single_contact, paramViewGroup, false);
localViewholder = new Viewholder();
localViewholder.tv_name = ((TextView) paramView
.findViewById(R.id.tv_name));
localViewholder.chk_id = ((CheckBox) paramView
.findViewById(R.id.chk_id));
paramView.setTag(localViewholder);
// dont need below line try without below line if it works comment it otherwise let it stay there.
paramView.setTag(R.id.chk_id, localViewholder.chk_id);
} else {
localViewholder = (Viewholder) paramView.getTag();
}
localViewholder.tv_name.setText(contArray.get(paramInt).get("serviceText"));
localViewholder.chk_id.setChecked(checked.get(paramInt));
localViewholder.chk_id.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
try {
if (isChecked) {
checked.set(paramInt, true);
Const.selectedIDs.add(contArray.get(paramInt));
Const.serviceArrayList.get(paramInt).put("flag", "1");
} else {
checked.set(paramInt, false);
Const.selectedIDs.remove(contArray.get(paramInt));
Const.serviceArrayList.get(paramInt).put("flag", "0");
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
return paramView;
}
public class Viewholder {
TextView tv_name;
CheckBox chk_id;
}
}
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).
Here is My code for item Click and print data in list view .
listView = (ListView) layout.findViewById(R.id.listView1);
Notifcationadapter adapter = new Notifcationadapter(this, notifies);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
View parentView = (View) view.getParent();
TextView value1 = ((TextView) parentView.findViewById(R.id.title));
String value = value1.getText().toString();
if (value.equals("Post"))
Toast.makeText(this, "Post", 1000).show();
if (value.equals("Request For travelling"))
Toast.makeText(this, "Request for travelling", 1000).show();
}
Here is my adapter :
public class Notifcationadapter extends BaseAdapter {
private static ArrayList<Notify> values;
Context context;
// List<RowItem> rowItems;
ViewHolder holder = null;
LinearLayout linear2;
DataBaseManager dbManager = new DataBaseManager(context);
ArrayList<Notify> notifies;
public Notifcationadapter(Context context, ArrayList<Notify> notifies) {
super();
this.context = context;
this.notifies = notifies;
}
/* private view holder class */
private class ViewHolder {
TextView txtTitle;
TextView txtDesc;
ImageView yesimage;
ImageView noimage;
TextView revresetime;
LinearLayout linear2;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.notifcationlistitem, null);
holder = new ViewHolder();
holder.linear2 = (LinearLayout) convertView.findViewById(R.id.linear2);
holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
holder.yesimage = (ImageView) convertView.findViewById(R.id.imageView1);
holder.noimage = (ImageView) convertView.findViewById(R.id.imageView2);
holder.revresetime = (TextView) convertView.findViewById(R.id.revresetime);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// holder.txtTitle.setText("Title");
String statustype = notifies.get(position).getNotificationType();
if (statustype.equals("1")) {
holder.txtDesc.setText(notifies.get(position).getNotificationDescrpiton());
holder.revresetime.setText(Functions.setLastSeenNotifcationTime(notifies.get(position).getNotificationDatetime()));
holder.txtTitle.setText("Request For travelling");
holder.yesimage.setVisibility(View.VISIBLE);
holder.noimage.setVisibility(View.VISIBLE);
} else {
holder.txtDesc.setText(notifies.get(position).getNotificationDescrpiton());
holder.txtTitle.setText("Post");
holder.revresetime.setText(Functions.setLastSeenNotifcationTime(notifies.get(position).getNotificationDatetime()));
holder.yesimage.setVisibility(View.GONE);
holder.noimage.setVisibility(View.GONE);
}
if (position % 2 == 0) {
convertView.setBackgroundColor(Color.parseColor("#ffffff"));
} else {
convertView.setBackgroundColor(Color.parseColor("#f5f6f1"));
}
holder.yesimage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(context, "Yes", 10000).show();
holder.linear2.setVisibility(View.INVISIBLE);
}
});
holder.noimage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "NO", 10000).show();
holder.linear2.setVisibility(View.INVISIBLE);
}
});
return convertView;
}
#Override
public int getCount() {
return notifies.size();
}
#Override
public Object getItem(int position) {
return notifies.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
}
I am displaying data in List view i wan i want to apply on item click function so that if text view list display post in list then its item click it should Print post if it Request for traveling then it should show Request for travel but i am unable to do this please help where am doing wrong .
you are getting the same value because of this line
TextView value1 = ((TextView) parentView.findViewById(R.id.title));
to get the String value in your adapter or arraylist you can do something like this.
i assume you have arraylist of objects
//you arraylist contains object/class
String value1 = notifies.get(position).getTitle();
and using the adapter
String value1 = adapter.getItem(position);
then #Override the getItem() function in your adapter
#Override
public String getItem(int position){
return notifies.get(position).getTitle();
}
then to move to other activity according to your if statement
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
View parentView = (View) view.getParent();
String value = notifies.get(position).getTitle();
Intent i = null;
if (value.equals("Post")){
i = new Intent(context,PostActivity.class);
}
else if (value.equals("Request For travelling")){
i = new Intent(context,RequestActivity.class);
}
if(i !=null){
startActivity(i);
}
}
I think you should use int position of onItemClick.
and then use if(notifies.get(position).getNotificationType() == 1)
it will be faster and should effectively work also.
First remove the onitemclick listener from activity. and use this code -
listView.setOnItemClickListener(this); // remove this line
as well as remove onitem click-
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
View parentView = (View) view.getParent();
TextView value1 = ((TextView) parentView.findViewById(R.id.title));
String value = value1.getText().toString();
if (value.equals("Post")) {
Toast.makeText(this, "Post", 1000).show();
}
if (value.equals("Request For travelling")) {
Toast.makeText(this, "Request for travelling", 1000).show();
}
}
**just add convertview click listener**
public class Notifcationadapter extends BaseAdapter {
private static ArrayList<Notify> values;
Context context;
// List<RowItem> rowItems;
ViewHolder holder = null;
LinearLayout linear2;
DataBaseManager dbManager = new DataBaseManager(context);
ArrayList<Notify> notifies;
public Notifcationadapter(Context context, ArrayList<Notify> notifies) {
super();
this.context = context;
this.notifies = notifies;
}
/* private view holder class */
private class ViewHolder {
TextView txtTitle;
TextView txtDesc;
ImageView yesimage;
ImageView noimage;
TextView revresetime;
LinearLayout linear2;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.notifcationlistitem, null);
holder = new ViewHolder();
holder.linear2 = (LinearLayout) convertView
.findViewById(R.id.linear2);
holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
holder.yesimage = (ImageView) convertView
.findViewById(R.id.imageView1);
holder.noimage = (ImageView) convertView
.findViewById(R.id.imageView2);
holder.revresetime = (TextView) convertView
.findViewById(R.id.revresetime);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// holder.txtTitle.setText("Title");
String statustype = notifies.get(position).getNotificationType();
if (statustype.equals("1")) {
holder.txtDesc.setText(notifies.get(position)
.getNotificationDescrpiton());
holder.revresetime.setText(Functions
.setLastSeenNotifcationTime(notifies.get(position)
.getNotificationDatetime()));
holder.txtTitle.setText("Request For travelling");
holder.yesimage.setVisibility(View.VISIBLE);
holder.noimage.setVisibility(View.VISIBLE);
}
else {
holder.txtDesc.setText(notifies.get(position)
.getNotificationDescrpiton());
holder.txtTitle.setText("Post");
holder.revresetime.setText(Functions
.setLastSeenNotifcationTime(notifies.get(position)
.getNotificationDatetime()));
holder.yesimage.setVisibility(View.GONE);
holder.noimage.setVisibility(View.GONE);
}
if (position % 2 == 0) {
convertView.setBackgroundColor(Color.parseColor("#ffffff"));
}
else {
convertView.setBackgroundColor(Color.parseColor("#f5f6f1"));
}
holder.yesimage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(context, "Yes", 10000).show();
holder.linear2.setVisibility(View.INVISIBLE);
}
});
holder.noimage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "NO", 10000).show();
holder.linear2.setVisibility(View.INVISIBLE);
}
});
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// write your code to redirect to another activity like this way
Intent i = new Intent(context,
Youractivity.class);
context.startActivity(i);
}
});
return convertView;
}
#Override
public int getCount() {
return notifies.size();
}
#Override
public Object getItem(int position) {
return notifies.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
}
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.