I have a list with items that have checkBox, and I need that only one checkBox to be selected at a time. I cannot use listView with singleChoice nor RadioButtons. Below is my code I am using but I do not know why is not working.
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (selectedCheckBox != null) {
// simulate radio group behavior
selectedCheckBox.setChecked(false);
selectedCheckBox = null;
}
if (isChecked) {
selectedCheckBox = (CheckBox) buttonView;
}
}
The problem is that the checkBoxes still remain checked and I do not know why regarding that I set the previous selectedCheckBox to false. Could anyone explain what happens? Thanks
UPDATE
I tested on a Nexus 5 with Android 5.0 and it works on that. On Android versions < 5.0 seems to have the problem I mentioned.
You need to call: notifyDataSetChanged() of your ListView Adapter. If not your data in your ListView is not going to refresh and your checkboxes will remain selected.
If you have one checkbox in each ListView item, you must loop the entire "other" (that must be unchecked) items, and uncheck it. It's not a practical approach.
I usually use a Arraylist to fill Listview. In array list there must be objects like boolean fields. So when a checkbox is checked or unchecked it means that the boolean field is changed to false or true, and then the list view is reproduced. If you follow this way, then it must be easy, first loop through Arraylist and change all booleans to false, then change the selected one to true, that is all, then android will refresh view for you. Hope it help.
Related
I have columns of checkboxes, the top row of which are CheckAll checkboxes for that particular column. If I uncheck the Checkall from the first CheckAll checkbox in the leftmost column I would like to uncheck the remaining CheckAll checkboxes.
However the mycheckbox.setSelected(false) has no effect. If however, I do a mycheckbox.setEnabled(false) (just as a test) it DOES work and the checkbox is disabled.
By the way, this is a "header row" for a listview with a custom adapter. The contents of the listview work as expected.
Any idea how to get the checkbox unchecked?
You should use mycheckbox.setChecked(false) instead of setSelected.
I've tried searching for setSelected to see what it does, but in official documentation of the CheckBox, I was not able to find it (which suggested to me that this method is probably found in one of the parent classes of CheckBox). Tried typing it in Android Studio:
CheckBox cb = new CheckBox(getApplication());
cb.setSelected(true);
Went to the implementation of the method (CTRL+Click) and saw this in the TextView class, from which almost every other widget is derived:
#Override
public void setSelected(boolean selected) {
boolean wasSelected = isSelected();
super.setSelected(selected);
if (selected != wasSelected && mEllipsize == TextUtils.TruncateAt.MARQUEE) {
if (selected) {
startMarquee();
} else {
stopMarquee();
}
}
}
Interesting thing to note here is that setChecked method is contained in the CompoundButton class, while setSelected is is TextView. That means that setSelected does something completely different because textView surely cannot be checked/unchecked.
I hope this explains it well.
When i click on the first item of ListView, the first item is selected. But when i scroll down, the 12th item is selected too, but i didn;t click on the 12th item. Why it was happend?
First screen: http://oi59.tinypic.com/9iw7b8.jpg
Second screen : oi60.tinypic.com/1zxunv4. jpg [delete whitespace]
My sourse code is like that :
http://startandroid.ru/en/uroki/vse-uroki-spiskom/85-urok-44-sobytija-v-listview.html
But i add the white recolor after utem click.
This question was answered here: Checking a checkbox in listview makes other random checkboxes checked too
Basically, when you scroll down you list, it recycles its present state as well as listeners attached to it.
One way I solved this problem is (suposing that your list is called check in java):
Create a boolean array (let's name it listCheck), same size as your checkbox, all values false
Write in your adapter getView method:
check.setChecked(listCheck[position]); //listCheck is your array of booleans.
check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckBox checkBox = (CheckBox) v.findViewById(R.id.checkEspecialidade);
listCheck[position] = check.isChecked();
}
});
Basically, we set the check value the same as the one on the array, and when the user clicks it, we also change de value of that check in the array. That works because the boolean array is not recycled.
I've been trying to figure out how to limit the number of checkable boxes in my preferences activity.
I'm using the preferences activity to make a number of select-able options but only want to let 5 be selected at a time. So once the fifth one is selected the others grey out. But when one is deselected the rest un-grey.
The only problem I'm having is that I cannot figure out how to set an OnClickListener to any of the preferences checkboxes or something similar.
Anyone have any ideas.
This is suppose to do the work assuming that you want to put listener on one checkbox.
final CheckBox checkBox = (CheckBox) findViewById(R.id.checkbox_id);
checkbox_id.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
//do whatever you wish to do when that checkbox is checked
}
}
);
Actually, I think I figured it out. What I was looking for is:
final CheckBoxPreference myBox = CheckBoxPreference)findPreference("CheckBoxItem");
Android version: 3.1 API version: Android 2.2 Device: Motorola MX604
I dynamically create a multi-select ListView of CheckedTextView items, and attach a OnItemClickListener to the ListView. In the onItemClick method of the listener, I invoke the isChecked method of CheckedTextView to determine if the associated checkbox is checked or unchecked. Simple enough.
The problem: When I select a previously unselected item, the isChecked method returns false. When I select a previously selected item, the method returns true. The checkbox icon itself checks and unchecks correctly.
Here is the layout for the CheckedTextView:
<CheckedTextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:textAppearance="?android:attr/textAppearanceLarge"
android:gravity="center_vertical"
android:drawableLeft="?android:attr/listChoiceIndicatorMultiple"
android:paddingLeft="6dip" android:paddingRight="6dip"
/>
This is how I create the ListView:
private void createSortedChannelList() {
emptyViewContainer();
ListView sortedListView = new ListView(this);
sortedListView.setId(CHANNEL_LISTVIEW_ID);
sortedListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
sortedListView.setItemsCanFocus(false);
sortedListView.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
CheckedTextView selectedItem = (CheckedTextView) view;
boolean isChecked = selectedItem.isChecked();
Log.e(mLogTag,"item clicked position = " + position + " isChecked = " + isChecked);
}
});
ArrayAdapter<Channel> listAdapter =
new ArrayAdapter<Channel>(this,R.layout.favorite_channel_list_select_channel_row,mAllChannels);
sortedListView.setAdapter(listAdapter);
for(int channelIndex = 0;channelIndex < mChannelIds.length;channelIndex++){
if(mSelectedChannelIds.contains(mChannelIds[channelIndex]))
sortedListView.setItemChecked(channelIndex, true);
}
addViewToViewContainer(sortedListView);
}
This is the log output that is produced when I select a previously unselected item:
09-23 09:08:59.650: item clicked position = 19 isChecked = false
and when I select a previously selected item
09-23 09:10:20.800: item clicked position = 18 isChecked = true
I have done an extensive search and I can only find one other report of similar behavior. This leads me to believe that the problem probably lies in my code, rather than the android class :p I have also looked at numerous examples that are set up in a similar fashion. Can anyone spot a problem?
thanks
PS This is my first post on any forum, so if I'm missing something that would be helpful to the readers of this post, please let me know.
I believe the code is behaving the way it should. Selecting a previously unselected method will invoke the click listener before changing the checked state of the item in the list. In other words, isChecked() won't return true for the previously unselected item until after the onClick() method is finished.
I've noticed that for me, at least, the behavior of when the state changes isn't consistent; on an emulator, isChecked() returned the pre-click state, but on a device it returned the post-click state.
I got around this by bypassing the "isChecked" altogether, and just looking at the state of the underlying object I am toggling, since that won't change unless I explicitly do so. However, this solution may depend on how your code is set up, and there may be other gotcha's that I am overlooking.
You should be using MultiChoiceModeListener for listening to checks. Here is the documentation
I am writing a music player that uses a custom Adapter extending BaseAdapter (efficiency adapter) that I want to display in an AlertDialog using setAdapter() where the user can either click on one of the songs to switch to that position in the playlist OR check songs to remove from the playlist. I tried using a custom click listener so that a user could just long click to remove the item from the list but the listview just doesn't work right... it was removing the wrong items (the ones at the end) even though the ArrayList contained the correct playlist items... (when I removed the item from the ArrayList, I passed it to the adapter which called notifyDataSetChanged... but that just didn't work as I mentioned. There is definitely a bug in the AlertDialog ListView... because there is no reason for it to have popped off the results from the end rather than the correct item.
So... the next method I would like to try is to use the setMultiChoiceItems() method of the AlertDialog... but it appears that it doesn't work with a custom adapter... only simple arrays. Will I have to subclass AlertDialog and Override the setMultiChoiceItems() method or is there a way I can make it work with an ArrayAdapter?
Basically, I can't figure out how to even iterate the list that the AlertDialog creates or whether it even passes that view somehow. In addition, I don't think I can even listen to clicks on checkboxes if I add those to the row. Any help will be greatly appreciated.
EDIT: Asking questions here is like magic... I answered my own question... this is how I did it. I added a hint to each checkbox which is the position of the item in the ArrayList. Then I used OnCheckedChangeListener to capture the selections. When you set a hint it adds text to the checkbox... since the background of the AlertDialog is white (even for clicked items?) I just set the hint text color to transparent.
holder.check.setHintTextColor(Color.TRANSPARENT);
holder.check.setHint(String.valueOf(position));
holder.check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
int position = Integer.parseInt((String) buttonView.getHint());
Log.v("onCheckedChanged", "Checked: "+isChecked+" returned: "+position+" which should be "+getItem(position).name);
}
});
Refer This and This
then
Pass a reference to byte[] in setMultiChoiceItems().
final boolean[] booleans = {false, true, false, true, false, false, false};
Then check the value of booleans inside setPositiveButton().
If you need to pass this AlertDialog around, then extend AlertDialog and have create a field boolean as described in 1.