I am getting information from my application in production, but when I am trying to reproduce the problem I am not able to do it. What I am looking for is any idea (as I am blocked) of how can I try to reproduce the error.
Basically I am having an activities with a listview, toolbar, edittext and admob advertisement.
My listview is composed of a relativealayout containing a textview and one imageview.
With the adapter I am attaching to the textview an OnLongClickListener that starts a drag operation.
To the Listview itself, I am adding an OnDragListener.
#TargetApi(11)
public class myDragEventListener implements View.OnDragListener {
// This is the method that the system calls when it dispatches a drag event to the
// listener.
public boolean onDrag(View v, DragEvent event) {
// Defines a variable to store the action type for the incoming event
final int action = event.getAction();
// Handles each of the expected events
switch(action) {
case DragEvent.ACTION_DRAG_STARTED:
return true;
case DragEvent.ACTION_DROP:
//We detect which is the item where the drop happened on.
int itemPosition = listShop.pointToPosition((int)event.getX(), (int)event.getY());
// An unknown action type was received.
default:
return true;
}
}
}
So, basically we initiate the drag on the textview from the listview item and the drop ends on the listview itself.
This code works properly, but I received from production reports that sometimes the value of itemPosition to be -1. To avoid an exception I can add a simple check, but I am worried about the user experience.
So, what I would like to avoid is a bad user experience with the application not responding properly, and we know is happening due to reports. The problem is that we are not able to reproduce.
Trying to reproduce this error we tried:
Longclick on textview and drop on imageview. (provides correct itemPosition)
Longclick on textivew and drop outside the listview (drag listener not called)
Longclick on textivew and drop at the edge of listview (works ok).
Does somebody has a suggestion of how this "-1" could be reproduced? Theoretically it should not happen.... is the drop (whatever the drag that has been initiated) activates the OnDragListener, that means that the position where the drop occurs is a position of the listview. How can the DragListener be called in a listview in an incorrect position?
Any idea what could be happening?
Ok, I found the problem. My listview covers almost all the screen, and sometimes is feed with items in the list that are not covering the complete list up to the end. When an item is dragged and dropped in the space where there is no item in the list, provide that value.
The problem is that my testing mobile is very small compared to other devices, and that mobile was always having the screen fully covered by items of the list, so any drag/drop operation was always captured.
I'm implementing a custom calendar using a GridView.
For this Calendar I have 3 view types, {DAY, TITLE, BLANK}
Is there a way to make certain items in a GridView not clickable?
What I'm trying to avoid is the press state animations for the items that aren't clickable. It ok it the user presses them, I can recognize that it's not the valid view in my onItemClickListener(). This is purely for UI purposes.
I found the solution. Don't know why I didn't search for ListViews in the first place.
You need to override the isEnabled() Function
Returning false will make it non-clickable. True will keep is clickable.
#Override
public boolean isEnabled(int position) {
switch(getItemViewType(position)) {
case CellTypes.BLANK:
case CellTypes.TITLE:
default :
return false;
case CellTypes.DAY:
return true;
}
}
In the adapter for your GridView, implement one of the get() method to return a reference to the object being clicked. I'm assuming that your adapter wraps a list of your "Calendar" objects.
In the onItemClickListener for your GridView, call get(index) or get(id) on the adapter to get a reference to the object being clicked. Check its type to see if it is one that you do not wish to be clickable, and return before executing the logic that is usually called when a clickable item is clicked.
In XML: android:clickable="false" and in code: setClickable(false);
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.
I'm porting an iPhone app into android app and one of the difficulties is recreating functionalities that are native to iPhone.
I found a native functionality of iPhone:
When user execute slide touch on a listed item in list view, a delete button appears.
Is there a version for this in android?
Can it be used and reused/customized?
This is just a bit more complicated to achieve. This is what I would do talking from a higher level.
Create a custom ViewGroup/Layout to hold a list item. Inside this layout you have your text lines images or what ever you have and also the delete button. You also here listen for gestures to hide or unhide the delete button.
In your list adapter you are going to need to keep track of which item is showing the delete button and which is not. Also, you are going to need to apply a click listener to each of the list item delete buttons. Every time you assign these states on the list item you should setTag(...) and store the list item position so that when it's clicked you can tell which item number must be deleted.
After deleting you must refresh the list in order for it to take effect. Depending on what type of adapter you are using that's going to determine how you refresh the adapter.
Hopefully this makes some sense. But I definitely think this is the easiest way since I've done this a couple times with similar functionality.
I guess you could either try to implement gesture listener over the listview itself but it might be hard to get the correct id. Since I haven't done it myself I can not answer exactly.
Otherwise you might be able to your own view as the item in the listview and the have a gesture listener on all the childs.
Fling gesture detection on grid layout
For some basic reading and code examples
I dont think there is any built-in API function to do this.
However, a workaround would be to use the onFling function on the view in listitem. You might be able to use this to accomplish what you want.
This is how I realize this effect. We have a ListView lvSimple and we add onTouchListener to our lvSimple. This is my working code.
float historicX = Float.NaN, historicY = Float.NaN;
static final int DELTA = 50;
enum Direction {LEFT, RIGHT;}
...
ListView lvSimple = (ListView) findViewById(R.id.linLayout);
...
lvSimple.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event)
{
// TODO Auto-generated method stub
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
historicX = event.getX();
historicY = event.getY();
break;
case MotionEvent.ACTION_UP:
if (event.getX() - historicX < -DELTA)
{
FunctionDeleteRowWhenSlidingLeft();
return true;
}
else if (event.getX() - historicX > DELTA)
{
FunctionDeleteRowWhenSlidingRight();
return true;
} break;
default: return false;
}
return false;
}
});
where function FunctionDeleteRowWhenSlidingLeft() is calling when when we sliding to the left, FunctionDeleteRowWhenSlidingRight - to the right respectively. In this function you need paste code for animation.
ps. I'm sorry for my bad english. Always glad to help.
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.