I'm using android:checkableBehavior="single" within a group, this group contains few items, those items represents content filters, there is no default filter(meaning there is not always has to be a checked item, at least that what I wants), if I click a filter and want to disable it I can click it again and my expectation is that by using setChecked(false) the item will unchecked.
However, it looks like:
For checkableBehavior="single" setChecked() will always check the menu
item even if parameter is 'false' because of Google implementation.
My obvious solution is adding a no filter item that can be checked by the users to indicates they don't want a filter but it's just seems more intuitive to check and uncheck the same item, it there another way to setChecked(false)?
Google's brain-dead implementation in MenuItemImpl (as of Nougat):
#Override
public MenuItem setChecked(boolean checked) {
if ((mFlags & EXCLUSIVE) != 0) {
// Call the method on the Menu since it knows about the others in this
// exclusive checkable group
mMenu.setExclusiveItemChecked(this);
} else {
setCheckedInt(checked);
}
return this;
}
Note that checked is completely ignored when the EXCLUSIVE flag is set.
It's taken me quite a while to get my head around the Android Spinner. After several failed implementation attempts, and after reading many questions partially similar to my own but without satisfactory answers, and some without any answers at all, e.g. here and here, I finally get that a "spinner" in Android isn't meant to be the same thing as a "drop-down list" from desktop apps, or a select in HTML. However, what my app (and I'm guessing the apps of all the other posters whose questions are similar) needs is something that works like a drop-down box, not like a spinner.
My two problems are with what I first considered to be idiosynchrasies the OnItemSelectedListener (I've seen these as separate questions on this site but not as one):
An initial selection of the first list item is triggered automatically without the user's interaction.
When the item that was already selected is selected again by the user, it is ignored.
Now I realise that, when you think about it, it makes sense for this to happen on a spinner - it has to start with a default value selected, and you spin it only to change that value, not to "re-select" a value - the documentation actually says: "This callback is invoked only when the newly selected position is different from the previously selected position". And I've seen answers suggesting that you set up a flag to ignore the first automatic selection - I guess I could live with that if there's no other way.
But since what I really want is a drop-down list which behaves as a drop-down list should (and as users can and should expect), what I need is something like a Spinner that behaves like a drop-down, like a combo-box. I don't care about any automatic pre-selection (that should happen without triggering my listener), and I want to know about every selection, even if it's the same one as previously (after all, the user selected the same item again).
So... is there something in Android that can do that, or some workaround to make a Spinner behave like a drop-down list? If there is a question like this one on this site that I haven't found, and which has a satisfactory answer, please let me know (in which case I sincerely apologise for repeating the question).
+1 to David's answer. However, here's an implementation suggestion that does not involve copy-pasting code from the source (which, by the way, looks exactly the same as David posted in 2.3 as well):
#Override
void setSelectionInt(int position, boolean animate) {
mOldSelectedPosition = INVALID_POSITION;
super.setSelectionInt(position, animate);
}
This way you'll trick the parent method into thinking it's a new position every time.
Alternatively, you could try setting the position to invalid when the spinner is clicked and setting it back in onNothingSelected. This is not as nice, because the user will not see what item is selected while the dialog is up.
Ok, I think I've come up with a solution for my own situation with the help of both David's and Felix' answer (I believe David's helped Felix', which in turn helped mine). I thought I'd post it here together with a code sample in case someone else finds this approach useful as well. It also solves both of my problems (both the unwanted automatic selection and the desired re-selection trigger).
What I've done is added a "please select" dummy item as the first item in my list (initially just to get around the automatic selection problem so that I could ignore when it was selected without user interaction), and then, when another item is selected and I've handled the selection, I simply reset the spinner to the dummy item (which gets ignored). Come to think of it, I should've thought of this long ago before deciding to post my question on this site, but things are always more obvious in hindsight... and I found that writing my question actually helped me to think about what I wanted to achieve.
Obviously, if having a dummy item doesn't fit your situation, this might not be the ideal solution for you, but since what I wanted was to trigger an action when the user selected a value (and having the value remain selected is not required in my specific case), this works just fine. I'll try to add a simplified code example (may not compile as is, I've ripped out a few bits from my working code and renamed things before pasting, but hopefully you'll get the idea) below.
First, the list activity (in my case) containing the spinner, let's call it MyListActivity:
public class MyListActivity extends ListActivity {
private Spinner mySpinner;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO: other code as required...
mySpinner = (Spinner) findViewById(R.id.mySpinner);
mySpinner.setAdapter(new MySpinnerAdapter(this));
mySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> aParentView,
View aView, int aPosition, long anId) {
if (aPosition == 0) {
Log.d(getClass().getName(), "Ignoring selection of dummy list item...");
} else {
Log.d(getClass().getName(), "Handling selection of actual list item...");
// TODO: insert code to handle selection
resetSelection();
}
}
#Override
public void onNothingSelected(AdapterView<?> anAdapterView) {
// do nothing
}
});
}
/**
* Reset the filter spinner selection to 0 - which is ignored in
* onItemSelected() - so that a subsequent selection of another item is
* triggered, regardless of whether it's the same item that was selected
* previously.
*/
protected void resetSelection() {
Log.d(getClass().getName(), "Resetting selection to 0 (i.e. 'please select' item).");
mySpinner.setSelection(0);
}
}
And the spinner adapter code could look something like this (could in fact be an inner class in the above list activity if you prefer):
public class MySpinnerAdapter extends BaseAdapter implements SpinnerAdapter {
private List<MyListItem> items; // replace MyListItem with your model object type
private Context context;
public MySpinnerAdapter(Context aContext) {
context = aContext;
items = new ArrayList<MyListItem>();
items.add(null); // add first dummy item - selection of this will be ignored
// TODO: add other items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int aPosition) {
return items.get(aPosition);
}
#Override
public long getItemId(int aPosition) {
return aPosition;
}
#Override
public View getView(int aPosition, View aView, ViewGroup aParent) {
TextView text = new TextView(context);
if (aPosition == 0) {
text.setText("-- Please select --"); // text for first dummy item
} else {
text.setText(items.get(aPosition).toString());
// or use whatever model attribute you'd like displayed instead of toString()
}
return text;
}
}
I guess (haven't tried this) the same effect could be achieved using setSelected(false) instead of setSelection(0), but re-setting to "please select" suits my purposes fine. And, "look, Ma, no flag!" (Although I guess ignoring 0 selections is not that dissimilar.)
Hopefully, this can help someone else out there with a similar use case. :-) For other use cases, Felix' answer may be more suitable (thanks Felix!).
Look. I don't know if this will help you, but since you seem tired of looking for an answer without much success, this idea may help you, who knows...
The Spinner class is derived from AbsSpinner. Inside this, there is this method:
void setSelectionInt(int position, boolean animate) {
if (position != mOldSelectedPosition) {
mBlockLayoutRequests = true;
int delta = position - mSelectedPosition;
setNextSelectedPositionInt(position);
layout(delta, animate);
mBlockLayoutRequests = false;
}
}
This is AFAIK taken from 1.5 source. Perhaps you could check that source, see how Spinner/AbsSpinner works, and maybe extend that class just enough to catch the proper method and not check if position != mOldSelectedPosition.
I mean... that's a huge "maybe" with a lot of "ifs" (android versioning comes to mind etc.), but since you seem frustrated (and I've been there with Android many times), maybe this can give you some "light". And I assume that there are no other obvious answers by looking at your previous research.
I wish you good luck!
Here is an alternative solution to differentiate between any (intended or unintended) programmatic and user-initiated changes:
Create your listener for the spinner as both an OnTouchListener and OnItemSelectedListener
public class SpinnerInteractionListener implements AdapterView.OnItemSelectedListener, View.OnTouchListener {
boolean userSelect = false;
#Override
public boolean onTouch(View v, MotionEvent event) {
userSelect = true;
return false;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (userSelect) {
// Your selection handling code here
userSelect = false;
}
}
}
Add the listener to the spinner registering for both event types
SpinnerInteractionListener listener = new SpinnerInteractionListener();
mSpinnerView.setOnTouchListener(listener);
mSpinnerView.setOnItemSelectedListener(listener);
This wouldn't handle the case in which the re-selection of the same item by the user doesn't trigger the onItemSelected method (which I have not observed), but I guess that could be handled by adding some code to the onTouch method.
Anyway, the problems Amos pointed out were driving me crazy before thinking of this solution, so I thought I'd share as widely as possible. There are many threads that discuss this, but I've only seen one other solution so far that is similar to this: https://stackoverflow.com/a/25070696/4556980.
Modifying the Spinner is useful if you want to have multiple selections simultaneously in the same activity.
If you only desire the user to have a hierarchical selection, for example:
What do you want to eat?
Fruit
Apples
Bananas
Oranges
Fast Food
Burgers
Fries
Hot dogs,
then the ExpandableListView might be better for you. It allows the user to navigate a hierarchy of different groups and choose a child element. This would be similar to having several Spinners for the user to choose from - if you do not desire a simultaneous selection, that is.
I worked through several of the issues mentioned in this thread before I realized that the PopupMenu widget is what I really wanted. That was easy to implement without the hacks and workarounds needed to change the functionality of a Spinner. PopupMenu was relatively new when this thread was started in 2011, but I hope this helps someone searching for similar functionality now.
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 need to handle the selected row in listview on long click on the row but because am using menus I can't override the onclicklistener. I am trying to do this:
listView.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
taskPosition = listView.getSelectedItemPosition();
return true;
}
});
but it doesn't work. Can anyone help me?
i got the value of listView.getSelectedItemPosition(); is equal -1
Of course. Rows typically are not selected. Rows are only selected if the user is using a pointing device (D-pad, trackball, etc.).
i need to handle the selection longclick on listview and use it in onContextItemSelected to perform action
No, you don't. You either use context menus or you use a long-click listener with a widget. You do not use both.
If you are trying to determine what row was long-clicked from onContextItemSelected(), here is a sample project that will demonstrate that for you, if your adapter is an ArrayAdapter. If you are using a CursorAdapter, here is a different sample project that will demonstrate this for you.
calling ListView's setSelection() seems to have a problem. a lot of people ask about it. there are answers but none is working. ignoring issues of visual affects. here's a basic scenario that results in unexpected results:
listView.setSelection(5); //listView is a ListView. there are >= 6 items in the list
int sel=listView.getSelectedItemPosition();
you would expect sel==5 but actually it's -1 (which method didn't work?)
so is this a bug and if not, what are the rules that govern the setting and retrieval of the selected item?
If you see in the documentation of setSelection you find this:
Sets the currently selected item. If
in touch mode, the item will not be
selected but it will still be
positioned appropriately. If the
specified selection position is less
than 0, then the item at position 0
will be selected.
That way, it makes perfectly sense that it returns -1. The item is not selected even if you run this method when you're in touch mode, as you most likely are.
I agree with Eric's answer. However, if you still want to make it work, here is a work around.
for your onItemClick part use the following (I had multiple listviews...)
public void onItemClick(AdapterView<?> parentView, View v, int chosenPosition, long
myLong) {
switch(parentView.getId()){
case R.id.Hrlist:
parentView.setSelection(chosenPosition);
break;
case R.id.Minlist:
parentView.setSelection(chosenPosition);
break;
case R.id.Seclist:
parentView.setSelection(chosenPosition);
}
}
Then in your other method you can use something along the lines of:
HrList.getFirstVisiblePosition();
Assuming HrList is defined as
ListView HrList = (ListView) findViewById(R.id.Hrlist);
So yes, in touch mode it doesn't register the item as selected. However, it does move it to a dependable location (i.e. at the top) which you can use to get the value.