CheckedTextView ListView with Headers - sort - android

I know this is not the first question about this topic with CheckBoxes and ListViews, but I don't know what to do..
I have a ListView with CheckedTextView and TextView and if I scroll some other's will get checked...
The views get resorted too and the enable/disable part (with the SharedPref) also don't work...
Used:
lalit3686 Blog
Android ListView Headers
So there is my code:
ActivtyMain.java
public class ActivityMain extends NavigationDrawerActivity{
#Override
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
super.onCreate(savedInstanceState);
context=this;
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
character_header_id.add(0);
character_header_id.add(character_original.size()+1);
character_header_id.add(character_original.size()+character_extension1.size()+2);
character_header_id.add(character_original.size()+character_extension1.size()+character_extension2.size()+3);
items.add(new CharacterHeader(getString(R.string.character_original)));
for(character key:character_original) {
String value=character_translation.get(key);
//System.out.println(value);
items.add(new CharacterListItem(value));
}
items.add(new CharacterHeader(getString(R.string.character_extension1)));
for(character key:character_extension1) {
String value=character_translation.get(key);
items.add(new CharacterListItem(value));
}
items.add(new CharacterHeader(getString(R.string.character_extension2)));
for(character key:character_extension2) {
String value=character_translation.get(key);
items.add(new CharacterListItem(value));
}
items.add(new CharacterHeader(getString(R.string.character_extension3)));
for(character key:character_extension3) {
String value=character_translation.get(key);
items.add(new CharacterListItem(value));
}
lv_charactere=((ListView) findViewById(R.id.character_list));
lv_charactere.setAdapter(new CharacterArrayAdapter(this, items));
//TODO check/unceck scroll problem
lv_charactere.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(!character_header_id.contains(position)) {
CheckedTextView ctv = (CheckedTextView) view.getTag(R.id.listitem_character);
//CheckedTextView ctv = (CheckedTextView) view.findViewById(R.id.list_character);
System.out.println("character:position:"+position);
NavigationDrawerActivity.setCharacterCheckedTextViewChecked(ctv);
}
}
});
}
CharacterArrayAdapter.java
public class CharacterArrayAdapter extends ArrayAdapter<Item> {
private LayoutInflater mInflater;
private List<Item> items;
public enum RowTypeText {
CHECKED_ITEM, TITLE_ITEM
}
public CharacterArrayAdapter(Context context, List<Item> items) {
super(context, 0, items);
mInflater = LayoutInflater.from(context);
this.items=items;
}
#Override
public int getViewTypeCount() {
return RowTypeText.values().length;
}
#Override
public int getItemViewType(int position) {
return getItem(position).getViewType();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = new ViewHolder();
if (convertView == null) {
if(items.get(position).getClass().equals(CharacterListItem.class)) {
convertView = mInflater.inflate(R.layout.character_list_item, null);
viewHolder.checkedtextview = (CheckedTextView) convertView.findViewById(R.id.listitem_character);
viewHolder.checkedtextview.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int getPosition = (Integer) v.getTag(); // Here we get the position that we have set for the checkbox using setTag.
CheckedTextView ctv=((CheckedTextView)((CharacterListItem)items.get(getPosition)).getView(mInflater, v));
//ctv.setChecked(!((CheckedTextView) v).isChecked()); // Set the value of checkbox to maintain its state.
NavigationDrawerActivity.setCharacterCheckedTextViewChecked(ctv);
System.out.println("character:position:"+getPosition);
}
});
viewHolder.checkedtextview.setTag(position);
convertView.setTag(viewHolder);
convertView.setTag(R.id.listitem_character, viewHolder.checkedtextview);
}else{
convertView = mInflater.inflate(R.layout.character_header, null);
viewHolder.textview=(TextView) convertView.findViewById(R.id.listheader_character);
convertView.setTag(viewHolder);
convertView.setTag(R.id.listheader_menu, viewHolder.textview);
}
}else{
viewHolder = (ViewHolder) convertView.getTag();
}
if(viewHolder.checkedtextview!=null) {
int pos=(int)viewHolder.checkedtextview.getTag(); // This line is important.
viewHolder.checkedtextview.setChecked(((CheckedTextView)((CharacterListItem)items.get(pos)).getView(mInflater, viewHolder.checkedtextview)).isChecked());
loadSettings(viewHolder, position);
return convertView;
}else{
return getItem(position).getView(mInflater, convertView);
}
//return getItem(position).getView(mInflater, convertView);
}
private void loadSettings(ViewHolder viewHolder, int position) {
//TODO select if selected before
for(Map.Entry<character, String> e:NavigationDrawerActivity.character_translation.entrySet()) {
if(e.getValue().equals(viewHolder.checkedtextview.getText())) {
if(NavigationDrawerActivity.character_playing.get(e.getKey())==0) {
viewHolder.checkedtextview.setChecked(false);
System.out.println("character:loadSaved: "+position+" checked:false");
}else{
if(viewHolder.checkedtextview.getText().equals(NavigationDrawerActivity.character_translation.get(character.DERNORMALEDORFBEWOHNER)) ||
viewHolder.checkedtextview.getText().equals(NavigationDrawerActivity.character_translation.get(character.WERWOLF))){
System.out.println("character:loadSaved: "+position+" disabled");
NavigationDrawerActivity.setCharacterCheckedTextViewEnabled(viewHolder.checkedtextview, false, true);
}else{
System.out.println("character:loadSaved: "+position+" checked:true");
viewHolder.checkedtextview.setChecked(true);
}
}
}
}
//TODO settings -> enable/disable
boolean ex1=NavigationDrawerActivity.spref.getBoolean(prefs.BOOLEAN_EXTENSION1.toString(), false);
boolean ex2=NavigationDrawerActivity.spref.getBoolean(prefs.BOOLEAN_EXTENSION2.toString(), false);
boolean ex3=NavigationDrawerActivity.spref.getBoolean(prefs.BOOLEAN_EXTENSION3.toString(), false);
for(Entry<character, String> e:NavigationDrawerActivity.character_translation.entrySet()) {
if(e.getValue().equals(viewHolder.checkedtextview.getText())) {
if(NavigationDrawerActivity.character_extension1.contains(e.getKey())) {
System.out.println("character:loadSaved: "+position+" enabled:"+ex1);
NavigationDrawerActivity.setCharacterCheckedTextViewEnabled(viewHolder.checkedtextview, ex1, false);
}
}
if(e.getValue().equals(viewHolder.checkedtextview.getText())) {
if(NavigationDrawerActivity.character_extension2.contains(e.getKey())) {
System.out.println("character:loadSaved: "+position+" enabled:"+ex2);
NavigationDrawerActivity.setCharacterCheckedTextViewEnabled(viewHolder.checkedtextview, ex2, false);
}
}
if(e.getValue().equals(viewHolder.checkedtextview.getText())) {
if(NavigationDrawerActivity.character_extension3.contains(e.getKey())) {
System.out.println("character:loadSaved: "+position+" enabled:"+ex3);
NavigationDrawerActivity.setCharacterCheckedTextViewEnabled(viewHolder.checkedtextview, ex3, false);
}
}
}
}
private static class ViewHolder{
protected CheckedTextView checkedtextview;
protected TextView textview;
}
}
NavigationDrawerActivity.java
public static void setCharacterCheckedTextViewChecked(CheckedTextView ctv) {
for(Entry<character, String> e:character_translation.entrySet()) {
if(e.getValue().equals(ctv.getText())) {
if(ctv.isChecked()) {
ctv.setChecked(false);
character_playing.put(e.getKey(),0);
}else{
ctv.setChecked(true);
if(e.getKey().equals(character.DERNORMALEDORFBEWOHNER) || e.getKey().equals(character.WERWOLF)) {
character_playing.put(e.getKey(),-1);
}else {
character_playing.put(e.getKey(),1);
}
}
break;
}
}
}
public static void setCharacterCheckedTextViewEnabled(CheckedTextView ctv, boolean enabled, boolean checked) {
ctv.setEnabled(enabled);
ctv.setClickable(enabled);
ctv.setLongClickable(enabled);
ctv.setChecked(checked);
}
ListViewCharacter.java
public class CharacterListItem implements Item {
private final String str;
public CharacterListItem(String text) {
this(text, false);
}
public CharacterListItem(String text, boolean selected) {
if(text==null) {
text="";
}
str=text;
}
#Override
public int getViewType() {
return RowTypeText.CHECKED_ITEM.ordinal();
}
#Override
public View getView(LayoutInflater inflater, View convertView) {
View view;
if (convertView == null) {
view = (View) inflater.inflate(R.layout.character_list_item, null);
} else {
view = convertView;
}
CheckedTextView tv=(CheckedTextView) view.findViewById(R.id.listitem_character);
tv.setText(str);
return view;
}
}
I think I posted all important code parts, if something is missing, please let me know
I don't know what to do..

getView
ViewHolder viewHolder = new ViewHolder();
if (convertView == null) {
if(items.get(position).getClass().equals(CharacterListItem.class)) {
convertView = mInflater.inflate(R.layout.character_list_item, null);
viewHolder.checkedtextview = (CheckedTextView) convertView.findViewById(R.id.listitem_character);
viewHolder.checkedtextview.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
onClickListener(v);
}
});
convertView.setTag(viewHolder);
convertView.setTag(R.id.listitem_character, viewHolder.checkedtextview);
}else{
convertView = mInflater.inflate(R.layout.character_header, null);
viewHolder.textview=(TextView) convertView.findViewById(R.id.listheader_character);
convertView.setTag(viewHolder);
convertView.setTag(R.id.listheader_menu, viewHolder.textview);
}
}else{
viewHolder = (ViewHolder) convertView.getTag();
}
if(viewHolder.checkedtextview!=null) {
viewHolder.checkedtextview.setTag(position); // This line is important.
viewHolder.checkedtextview.setText(items.get(position).getText());;
loadSettings(viewHolder);
return convertView;
}else{
return getItem(position).getView(mInflater, convertView);
}
important change (I think so):
only on the second part to set the position

Related

listview is not refreshing values after deleting row with checkbox value = true

Good day,
I'm doing a listview, baseadapter with checkbox that is able to delete multiple selected rows.
here is my onCreate :
ArrayList<Memos> list;
list = new ArrayList<Memos>();
list.add(new Memos(1, "s", "s"));
list.add(new Memos(2, "x", "aaa"));
list.add(new Memos(3, "v", "aesf"));
final ListView lv = (ListView) findViewById(R.id.myList);
lv.setAdapter(new MemoListAdapter(list, this));
deletebutton
#Override
public void onClick(View v) {
MemoListAdapter myAdapter = (MemoListAdapter)lv.getAdapter();
myAdapter.remove();
}
then here is my complete baseadapter :
public class MemoListAdapter extends BaseAdapter {
private List<Memos> listComment;
private Context context;
private LayoutInflater inflater = null;
private ArrayList<Memos> deleteMemos;
public MemoListAdapter(List<Memos> listComment, Context context) {
super();
this.listComment = listComment;
this.context = context;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
deleteMemos = new ArrayList<Memos>();
}
#Override
public int getCount() {
return listComment.size();
}
#Override
public Memos getItem(int position) {
return listComment.get(position);
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
public class ViewHolder
{
TextView body;
TextView date;
CheckBox checkBox;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_view, null);
holder = new ViewHolder();
holder.body = (TextView) convertView.findViewById(R.id.big_text);
holder.date = (TextView) convertView.findViewById(R.id.small_text);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkbox);
holder.body.setText(listComment.get(position).getMessageBody());
holder.date.setText(listComment.get(position).getMessageDate());
holder.checkBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//is chkIos checked?
if(listComment.get(position).isCheckbox()) {
holder.checkBox.setChecked(false);
deleteMemos.remove(listComment.get(position));
}
else {
// Do invisible or gone stuff here
holder.checkBox.setChecked(true);
deleteMemos.add(listComment.get(position));
}
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
public void remove() {
for(Memos memo : deleteMemos) {
listComment.remove(memo);
}
this.notifyDataSetChanged();
}
}
after selecting rows to delete (4 rows)
the list adjusted but the contents and the check value of the checkbox is still the same.
I am wondering what part of the notifyDataSetChanged is wrong.
Thanks in advance!
Your views are reused that's why it happen . Try adding below codes into your getView()
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_view, null);
holder = new ViewHolder();
holder.body = (TextView) convertView.findViewById(R.id.big_text);
holder.date = (TextView) convertView.findViewById(R.id.small_text);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkbox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if(listComment.get(position).isCheckbox()) {
holder.checkBox.setChecked(true);
}else {
holder.checkBox.setChecked(false);
}
holder.body.setText(listComment.get(position).getMessageBody());
holder.date.setText(listComment.get(position).getMessageDate());
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
listComment.get(position).setIsCheckbox(isChecked);
if (isChecked){
deleteMemos.add(listComment.get(position));
}else{
deleteMemos.remove(listComment.get(position));
}
}
});
return convertView;
}

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).

CustomListView with checkbox issues?

Hi I've created CustomListView with checkbox. When I click first item, it automaically enable third item also. How to solve it?
holder.orderCheckBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(((CheckBox)v).isChecked()) {
checkboxstate[position]=true;
if(observationDetailsList.get(position).LaboratoryUid.toString().equalsIgnoreCase(GlobalVariables.UUIDEmpty.toString()))
{
displayWarning();
}
patientOrderList.add(orderDetailsList.get(position));
patientObservationList.add(observationDetailsList.get(position));
} else {
checkboxstate[position]=false;
patientOrderList.remove(orderDetailsList.get(position));
patientObservationList.remove(observationDetailsList.get(position));
}
}
});
Here is the complete adapter class to handle this
i am using a toogle button for that and the same you can do with check box you have to maintain state of check boxes
public class SettingsListAdapter extends BaseAdapter implements
{
private LayoutInflater mInflater;
private DealsSTRUC[] setings_Adapt_Catagories;
Context mContext;
String isNotificationEnnabled;
public SettingsListAdapter( Context context, DealsSTRUC[] catagories ,String isEnnabled)
{
mContext = context;
setings_Adapt_Catagories = catagories;
mInflater = LayoutInflater.from(context);
isNotificationEnnabled=isEnnabled;
}
#Override
public int getCount()
{
return setings_Adapt_Catagories.length;
}
#Override
public Object getItem(int arg0)
{
return null;
}
#Override
public long getItemId(int position)
{
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
SettingsAdptorViewHolder holder;
if (convertView == null)
{
convertView = mInflater.inflate(R.layout.adapter_settingslist, null);
holder = new SettingsAdptorViewHolder();
holder.settings_catagory = (TextView) convertView.findViewById(R.id.settings_lable_text);
holder.settings_list_checkbox = (ToggleButton) convertView.findViewById(R.id.settings_checkbox);
holder.settings_list_checkbox.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
ToggleButton cb = (ToggleButton) v;
if (cb.isChecked() == true)
{
setings_Adapt_Catagories[position].setStatus("true");
}
else
{
setings_Adapt_Catagories[position].setStatus("false");
}
}
});
convertView.setTag(holder);
}
else
{
holder = (SettingsAdptorViewHolder) convertView.getTag();
}
if(setings_Adapt_Catagories[position].getStatus().equals("true")&&isNotificationEnnabled.equals("on"))
{
holder.settings_list_checkbox.setChecked(true);
}
else if(setings_Adapt_Catagories[position].getStatus().equals("false"))
{
holder.settings_list_checkbox.setChecked(false);
}
holder.settings_catagory.setText(setings_Adapt_Catagories[position].getDealName());
return convertView;
}
class SettingsAdptorViewHolder
{
TextView settings_catagory;
ToggleButton settings_list_checkbox;
}
}

how to limit checkbox selection in listview?

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.

Categories

Resources