select all checkboxes of Listview in android - android

I'am having Custom dialog in which i've displayed a listView with checkboxes.I want to select all checkBoxes of ListView by Clicking button in dialog.
here is my button onClickListener
selectAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (int i = 0; i < listView.getChildCount(); i++) {
LinearLayout myLayout =(LinearLayout)listView.getChildAt(i);
CheckBox cb = (CheckBox) myLayout.findViewById(R.id.checkbox);
cb.setChecked(true);
}
}
});
with above code i have can only check those checkboxes which are on view.
I know this happens because listView reuses views.
please suggest me what to do

You can add boolean variable into your model class and set true on your button click listener, check this:
class YourModel{
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
}
Your button onClick change.
public void onClick(View view) {
for (int i = 0; i < yourArrayList.size(); i++) {
yourArrayList.get(i).setSelected(true);
}
yourAdapter.notifyDataSetChanged();
}
your adapter getView method
public View getView ( final int position, View convertView, ViewGroup parent){
CheckBox cb = (CheckBox) myLayout.findViewById(R.id.checkbox);
cb.setChecked(yourModel.isSelected());
}

Related

how to get checked multiple values using custom adapter in android

I have listview with custom adapter. Every element of this listview has checkbox. Standart function .isChecked() does not work.
someActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
btnShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
List<Boolean> listCheck;
listCheck = new ArrayList<Boolean>();
for (int i = 0; i < CA_main_trx.editModelArrayList.size(); i++){
Boolean stat = CA_main_trx.editModelArrayList.get(i).getCheckShare();
String nilaiPcs = CA_main_trx.editModelArrayList.get(i).getTextView_main_trx2();
Log.d(TAG, "onClick: --a" + nilaiPcs);
Log.d(TAG, "onClick: --a" + stat);
}
}
});
CustomeAdapter
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
final String TAG = "CA_Main_Trx : ";
...
holder.checkShare.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b){
String id = editModelArrayList.get(position).getTextView_main_trx0();
Log.d(TAG, "onCheckedChanged: True"+id);
}
else
Log.d(TAG, "onCheckedChanged: False");
}
});
...
model
package com.m.t;
public class EM_main_trx {
private boolean checkShare;
public Boolean getCheckShare() {return checkShare;}
public void setCheckShare(Boolean checkShare) {
this.checkShare = checkShare;
}
}
When checked in custome Adapter i get the checked status. But when i get the data using button in my mainactivity i got stuck. just got null.
Some my reference :
Android: Get checked checkbox values
Finding the Checked state of checkbox in a custom listview
how to get the the multiple checkbox values using custom adapter in android
Android List View Custom Adapter with Checkbox multiple selection and Search Listview
Checked values of CheckBox with Custom Listview android
Just update part of custome adapter to this :
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
editModelArrayList.get(position).setCheckShare(b);
}

How can I select only one Checkbox in a dynamic view

I have a screen that add dynamically a row with two textView and one CheckBox. My problem is that I only want that the user could check one, and the others have to be uncheck. If the user push another checkbox, enable this and disable all the other checkbox. I've test some things but I don't get the functionality that I want.
I can't change the configuration from checkbox to radioButton and I have to use the method that I'm using:
private selected_position = -1;
protected void addGreetingToListView(final GreetingListJson greetings) {
View row = inflater.inflate(R.layout.main_greetings_settings_row, greetingListView, false);
row.setTag(greetings);
playButton = (ToggleButton) row.findViewById(R.id.detail_play_greeting);
TextView greetingName = (TextView)row.findViewById(R.id.greetingTitle);
greetingName.setDuplicateParentStateEnabled(true);
TextView greetingDescription = (TextView)row.findViewById(R.id.greetingDescription);
greetingDescription.setDuplicateParentStateEnabled(true);
checkBox = (CheckBox) row.findViewById(R.id.checkBox_greeting_list);
checkBox.setTag(greetings);
checkBox.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick (View view) {
if (((CheckBox) view).isChecked())
{
selected_position= greetingListView.getChildCount();
}
else
{
selected_position=-1;
}
}
});
greetingName.setText(greetings.Name);
greetingDescription.setText(greetings.Description);
row.setOnClickListener(this);
row.setOnLongClickListener(this);
row.setFocusable(true);
greetingListView.addView(row);
}
The XML of the Checkbox:
<CheckBox
android:id="#+id/checkBox_greeting_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="15dp"
android:layout_centerVertical="true"/>
Firstly, declare an ArrayList in the class:
ArrayList<CheckBox> mCheckBoxes = new ArrayList<CheckBox>();
Then in addGreetingToListView add every new checkbox to mCheckBoxes and modify the click listener of the checkbox:
checkBox.setTag(greetings);
mCheckBoxes.add(checkBox);
checkBox.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick (View view) {
if (((CheckBox) view).isChecked())
{
for (int i = 0; i < mCheckBoxes.size(); i++) {
if (mCheckBoxes.get(i) == view)
selected_position = i;
else
mCheckBoxes.get(i).setChecked(false);
}
}
else
{
selected_position=-1;
}
}
});

Having problems while trying to delete single rows from a custom ToDo list?

I want to delete selected rows from a todo list by clicking on the checkbox and deleting them trough the delete button, for that I am within my custom adapter setting a setOnCheckedChangeListener on my checkbox and setOnClickListener on my delete button, now keep in mind that the delete button is inflated on my fragment view and I am using it on my row view, but the problem is only the last element from my todo list is getting deleted not the rest of them, I tried working within the fragment view and notify the adapter later on but all I got was a null pointer error on my checkbox.
Row View:
todoCheckBox = (CheckBox) convertView.findViewById(R.id.todo_CheckBox);
todoTextView.setText(values.get(position));
todoCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//Toast.makeText(getContext(), " CheckBox Status: " + isChecked, Toast.LENGTH_LONG).show();
mDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mDelete.isPressed() && (todoCheckBox.isChecked())) {
//convertView.clearFocus(position);
mAdapter.clear();
//mAdapter.notifyDataSetChanged();
}
}
});
}
});
Fragment View:
#TargetApi(9) // remember this for isEmpty()
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_todo, container, false);
ArrayList<String> todoList = new ArrayList<String>();
mAdapter = new UsersAdapter(getActivity(), todoList);
listViewToDo = (ListView) v.findViewById (android.R.id.list);
listViewToDo.setAdapter(mAdapter);
mToDoField = (EditText) v.findViewById(R.id.todo_editText);
mDelete = (Button) v.findViewById(R.id.delete_button);
mAdd = (Button)v.findViewById(R.id.add_button);
mAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String toDo = mToDoField.getText().toString().trim();
if (toDo.isEmpty()){
return;
}
mAdapter.add(toDo);
mToDoField.setText("");
}
});
return v;
}
}
You need to assign an onclick listener to your delete button outside of the onChecked statement. Add it in code just after you assign the onClick event to the add button. This is because a view in android can only have 1 listener per event type.
The onClick event can look something like below using a sparese
mDelete.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
SparseBooleanArray checked = listViewToDo.getCheckedItemPositions();
for (int i = 0; i < listViewToDo.getCount(); i++){
if (checked.get(i)==true)
{
mAdapter.remove(i);
}
mAdapter.notifyDataSetChanged();
}
listViewToDo.clearChoices();
}
});

How to get selected list items from a Listview with checkBox and Custom Adapter?

I have a ListView with CheckBox on it. and i am using Custom Adapter to populate the ListView.
In my xml file i have a Button at bottom. what i want is let user select number of rows in ListView and when he/she clicked on the Button get the position of the selected items so that i could get the object for particular row for further calculations.
In the customadapter's getview method, do
//use the actual id of your checkbox of course
Checkbox checkbox = (CheckBox)findViewById(R.id.checkbox);
checkbox.setFocusable(false);
checkbox.setFocusableInTouchMode(false);
now the checkbox is clickable as is the listitem.
To solve this problem you will have to create a custom Item class which will represent your individual checkboxes on the list. The array of these items will then be used by the adapter class to display your check boxes.
This Item class will have a boolean variable isSelected which will determine if the checkbox is selected or not. You will have to set the value of this variable in your OnClick Method of your custom adapter class
For Example
class CheckBoxItem{
boolean isSelected;
public void setSelected(boolean val) {
this.isSelected = val;
}
boolean isSelected(){
return isSelected;
}
}
For your CustomAdapter Class which look like following:
public class ItemsAdapter extends ArrayAdapter implements OnClickListener {
// you will have to initialize below in the constructor
CheckBoxItem items[];
// You will have to create your check boxes here and set the position of your check box
/// with help of setTag method of View as defined in below method, you will use this later // in your onClick method
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
CheckBox cBox = null;
if (v == null) {
LayoutInflater vi = (LayoutInflater) apUI.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.attachphoto, null);
}
CheckBoxItemItem it = items[position];
cBox =(CheckBox) v.findViewById(R.id.apCheckBox);
cBox.setOnClickListener(this);
cBox.setTag(""+position);
Log.d(TAG, " CHECK BOX IS: "+cBox+ " Check Box selected Value: "+cBox.isChecked()+" Selection: "+it.isSelected());
if(cBox != null){
cBox.setText("");
cBox.setChecked(it.isSelected());
}
return v;
}
public void onClick(View v) {
CheckBox cBox =(CheckBox) v.findViewById(R.id.apCheckBox);
int position = Integer.parseInt((String) v.getTag());
Log.d(TAG, "CLicked ..."+cBox.isChecked());
items[position].setSelected(cBox.isChecked());
}
}
Later you will will declare and array of your CheckBoxItem class which will be contained by your Adapter class in this case it will be ItemsAdapter class.
Then when the user presses the button you can iterate through all the items in the array and check which one is selected by using the isSelected() method of CheckBoxItem class.
In your activity you will have:
ArrayList getSelectedItems(){
ArrayList selectedItems = new ArrayList();
int size = items.length;
for(int i = 0; i<size; i++){
CheckBoxItem cItem = items[i];
if(cItem.isSelected()){
selectedItems.add(cItem);
}
}
return selectedItems;
}
I had the exact same problem. I solved it in this way
public class myActivity extends Activity {
//ActionBarSherlock mSherlock = ActionBarSherlock.wrap(this);
public ListView listview;
private ArrayList<Object> itemlist=new ArrayList<Object>();
Button button;
private myAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview=(ListView)findViewById(R.id.listview1);
button=(Button)findViewById(R.id.button1);
/*add some data to ur list*/ itemlist.add(something);
adapter=new Adapter(myActivity.this, 0, itemlist);
listview.setAdapter(adapter);
**listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listview.setItemsCanFocus(false);**
button.setOnClickListner(new OnClickListner()
{
#Override
public void OnClick(View v)
{
/* this returns the checked item positions in the listview*/
**ArrayList<Integer> itempositions=adapter.getcheckeditemcount();**
for(int i:itempositions)
{
/* This is the main part...u can retrieve the object in the listview which is checked and do further calculations with it*/
**Object info=adapter.getItem(i);**
Log.d(TAG,"checked object info= ",info.something);
}
}
});
}
private class myAdapter extends ArrayAdapter<Object> {
private Context context;
private ArrayList<Object> list;
**private ArrayList<Integer> checkedpositions;**
public myAdapter(Context localContext,int textViewResourceId, ArrayList<Object> objects) {
super(localContext,textViewResourceId,objects);
context = localContext;
this.list=objects;
this.checkedpositions=new ArrayList<Integer>();
//Log.d("adapter","list size= "+objects.size());
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView picturesView;
View v = convertView;
TextView Mainitem;
final CheckBox check;
if (v == null)
{
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.albumview, null);
Object item=list.get(position);
if(item!=null)
{
check = (CheckBox)v.findViewById(R.id.checkBox1);
/* set a tag for chekbox with the current view position */
**check.setTag(position);**
/*set a onchecked change listner for listning to state of checkbox toggle */
check.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
/*get the tag of the checkbox...in this case this will give the (position of view)*/
Object tag=check.getTag();
if ( isChecked )
{
// perform logic
count++;
Log.d("Checkbox","added "+tag);
checkedpositions.add((Integer) tag);
}
else
{
count--;
checkedpositions.remove(tag);
Log.d("Checkbox","removed "+(Integer)tag);
}
/* if u dont have a textview in ur listview then ignore this part */
Mainitem = (TextView) v.findViewById(R.id.textView1);
Mainitem.setText(item.Album_name);
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d("error", "wall");
}
}
}
return v;
}
/* Finally create a method which return the checkeditem postions in the listview */
**public ArrayList<Integer> getcheckeditemcount()
{
return this.checkedpositions;
}**
}
}
I hope this helps.

Android ListItem with radio button

My page has a listView and a OK button. Each listItem has an id and RadioButtonGroup.
I am using SimpleCursorAdapter to load the list.
What I would like to do is when I click on OK, I want to get individual id and radio button selection from that radioButtonGroup.
How do I do it ?
You can add a clicklistener to your list:
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
RadioButton button = (RadioButton) view.findViewById(R.id.RadioButton);
button.getId();
}
});
You have to extend the SimpleCursorAdapter class and inside the newView / bindView methods you need to check for the state of the radioButtonGroup. In order to do that you need to set a listener for your radio button group using the OnCheckedChangedListener. I have some source code example that I used on a personal app. Bare in mind that I'm listening to checkboxes but is should be perfectly straight forward to adapt to a radio button group.
#Override
public void bindView(View view, Context context, Cursor cursor) {
NoteHolder holder = (NoteHolder) view.getTag();
holder.titleView.setText(cursor.getString(titleColIndex));
holder.modifiedView.setText(mUtils.formatDate(mUtils.formatDateFromString (cursor.getString(modifiedColIndex), context, "dd-MM-yyyy"), "dd-MM-yyyy"));
holder.priorityView.setImageResource(mUtils.getPriorityResourceId(cursor.getInt(priorityColIndex)));
Typeface tf = Typeface.createFromAsset(context.getAssets(), "fonts/ARLRDBD.TTF");
holder.titleView.setTypeface(tf);
holder.modifiedView.setTypeface(tf);
final int pos = cursor.getPosition();
final long id = cursor.getLong(idColIndex);
holder.checkbox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
checkChecked(v, pos, id);
}
});
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
rowCheckChecked(v, pos, id);
}
});
holder.checkbox.setChecked(itemChecked.get(pos));
}
private static class NoteHolder {
TextView titleView;
TextView modifiedView;
ImageView priorityView;
CheckBox checkbox;
}
private void checkChecked(View v, int pos, long id){
CheckBox cb = (CheckBox) v.findViewById(R.id.delete_checkbox);
if (cb.isChecked())
{
itemChecked.set(pos, true);
mSelectedIDs.add(id);
}
else if(!cb.isChecked())
{
itemChecked.set(pos, false);
if(mSelectedIDs.contains(id))
mSelectedIDs.remove(id);
}
}
I would advise you to use a viewHolder pattern too. Specially if your app is going to have many list items. You can read more about it here and see an example here, you can also see it implemented in the code I've put above.
Hope that helps.

Categories

Resources