Android ListView tolerance - android

I have list items that have a HorizontalScrollView in each of them. Hence, I should be able to swipe up and down the list and also swipe through the list item horizontally. (e.g. Pulse News App).
What I'm encountering is that, whenever I scroll the HorizontalScrollView, the ListView also gets scrolled by tiny bit but giving out annoying disturbances in terms of User Experience.
So, I was actually thinking to subclass ListView and implement my own ListView widget. However, I don't know which method to override so that I could increase X tolerance and stop the listview from giving these unwanted flickering.

gestureDetector = new GestureDetector(new YScrollDetector());
public boolean onInterceptTouchEvent(MotionEvent ev) {
//Call super first because it does some hidden motion event handling
boolean result = super.onInterceptTouchEvent(ev);
//Now see if we are scrolling vertically with the custom gesture detector
if (gestureDetector.onTouchEvent(ev)) {
return result;
}
//If not scrolling vertically (more y than x), don't hijack the event.
else {
return false;
}
}
// Return false if we're scrolling in the x direction
class YScrollDetector extends SimpleOnGestureListener {
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
try {
if (Math.abs(distanceY) > Math.abs(distanceX)) {
return true;
} else {
return false;
}
} catch (Exception e) {
// nothing
}
return false;
}
}
This is will help you, you have to override these in the custom list view you create,i used this to eliminate the problem in my application. Hope this helps.

Related

How to add a gesture detector to a view in Android

I was struggling with adding a gesture detector to a subview in my project. Do I override the parent's onTouchEvent or the child's onTouchEvent? Do I make an OnTouchListener and add the gesture detector there? The documentation shows an example for how to add a gesture detector to the activity itself but it is not clear how to add it to a view. The same process could be used if subclassing a view (example here), but I want to add the gesture without subclassing anything.
This is the closest other question I could find but it is specific to a fling gesture on an ImageView, not to the general case of any View. Also there is some disagreement in those answers about when to return true or false.
To help myself understand how it works, I made a stand alone project. My answer is below.
This example shows how to add a gesture detector to a view. The layout is just a single View inside of an Activity. You can use the same method to add a gesture detector to any type of view.
We will add the gesture detector to the green View.
MainActivity.java
The basic idea is to add an OnTouchListener to the view. Normally we would get all the raw touch data here (like ACTION_DOWN, ACTION_MOVE, ACTION_UP, etc.), but instead of handling it ourselves, we will forward it on to a gesture detector to do the interpretation of the touch data.
We are using a SimpleOnGestureListener. The nice thing about this gesture detector is that we only need to override the gestures that we need. In the example here I included a lot of them. You can remove the ones you don't need. (You should always return true in onDown(), though. Returning true means that we are handling the event. Returning false will make the system stop giving us any more touch events.)
public class MainActivity extends AppCompatActivity {
private GestureDetector mDetector;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// this is the view we will add the gesture detector to
View myView = findViewById(R.id.my_view);
// get the gesture detector
mDetector = new GestureDetector(this, new MyGestureListener());
// Add a touch listener to the view
// The touch listener passes all its events on to the gesture detector
myView.setOnTouchListener(touchListener);
}
// This touch listener passes everything on to the gesture detector.
// That saves us the trouble of interpreting the raw touch events
// ourselves.
View.OnTouchListener touchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// pass the events to the gesture detector
// a return value of true means the detector is handling it
// a return value of false means the detector didn't
// recognize the event
return mDetector.onTouchEvent(event);
}
};
// In the SimpleOnGestureListener subclass you should override
// onDown and any other gesture that you want to detect.
class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
#Override
public boolean onDown(MotionEvent event) {
Log.d("TAG","onDown: ");
// don't return false here or else none of the other
// gestures will work
return true;
}
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
Log.i("TAG", "onSingleTapConfirmed: ");
return true;
}
#Override
public void onLongPress(MotionEvent e) {
Log.i("TAG", "onLongPress: ");
}
#Override
public boolean onDoubleTap(MotionEvent e) {
Log.i("TAG", "onDoubleTap: ");
return true;
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
Log.i("TAG", "onScroll: ");
return true;
}
#Override
public boolean onFling(MotionEvent event1, MotionEvent event2,
float velocityX, float velocityY) {
Log.d("TAG", "onFling: ");
return true;
}
}
}
It is a quick setup to run this project, so I recommend you try it out. Notice how and when the log events occur.
short version in kotlin to detect double tap only for a view:
val gestureDetector = GestureDetector(activity, object : GestureDetector.SimpleOnGestureListener() {
override fun onDoubleTap(e: MotionEvent?): Boolean {
Log.d("myApp", "double tap")
return true
}
})
myView.setOnTouchListener { _, event -> gestureDetector.onTouchEvent(event) }
and don't forget to make myView clickable

Handle a fling/scroll in Android without consuming the MotionEvent

I've got a ViewFlipper at the side of the screen in my app containing a bunch of different views, and I would like the user to be able to dismiss this by swiping to the left. So I did the usual...
private class SwipeDetector extends SimpleOnGestureListener {
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
//Dismiss view
}
#Override
public boolean onDown(MotionEvent e) {
return true;
}
}
...and then set the onTouchListener of the ViewFlipper to call onTouchEvent in SwipeDetector. It all worked great, however I then noticed because it was consuming all the touch events going into the ViewFlipper, I couldn't click anything when the ViewFlipper itself. If I don't override onDown or I make it return false then the TouchListener ignores the rest of the event and I don't get the fling. I'm happy to hack together some kind of custom swipe detection if I could even handle all the ACTION_MOVE events following the user touching the ViewFlipper but can't even do that. Is there any way to keep listening to the MotionEvent without consuming the onDown?
What works for me is extending View.OnTouchListener instead of SimpleGestureListener, and override onTouch method. Please, take this snippet as a very simple (and improvable) approach to get horizontal swipe detection.-
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
downX = event.getX();
return true;
}
case MotionEvent.ACTION_UP: {
upX = event.getX();
float deltaX = downX - upX;
if (Math.abs(deltaX) > MIN_DISTANCE) {
if (deltaX < 0) {
this.onLeftToRightSwipe();
return true;
}
if (deltaX > 0) {
this.onRightToLeftSwipe();
return true;
}
return true;
}
return true;
}
}
return false;
}
Did you notice the GestureDetector? It is available since API Version 1.
http://developer.android.com/reference/android/view/GestureDetector.OnGestureListener.html
Both fling and scroll gestures are handled.

Android. How to get layout values from views in TabHost?

I have a TabHost hosting 3 Activities. In addition to the tabs, I want support for swipe gestures to change the current tab. My issue is that one of the views holds a horizontal scrollview, and I cannot figure out how to prevent touches in the horizontal scrollview from changing the current tab.
plateView is the horizontal scrollview that needs to be handled. Finding it's bottom with plateView.getBottom() and not counting touches above that works without the TabHost, but now it returns null and crashes, regardless of where it's called.
onTouchEvent counts touches everywhere and dispatchTouchEvent doesn't count touches on any widget. It seems some combination of them would be great, but together they yield the same functionality as onTouchEvent alone. Swipes anywhere count to change the Activity. My understanding of these is a little fuzzy though.
Why does getBottom() return null? How can I get this to work?
gestureDetector = new GestureDetector(new CalcGestureDetector());
gestureListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Log.d(TAG,"onTOUCH");
if(gestureDetector.onTouchEvent(event)){
return true;
}
return false;
}
};
//Takes the touch and interprets it. Handles it. Changes tabs on fling.
class CalcGestureDetector extends SimpleOnGestureListener{
#Override
public boolean onFling(MotionEvent eOne, MotionEvent eTwo, float velocityX, float velocityY){
Log.d(TAG,"WTF "+plateView.getBottom());
if(false){
}
else{
try{
if (Math.abs(eOne.getY() - eTwo.getY()) > flingMaxOffPath)
return false; //Too much of an arc in the fling.
// right to left swipe
if(eOne.getX() - eTwo.getX() > flingMinDistance && Math.abs(velocityX) > flingMinVelocity) {
tabHost.setAnimation(slideLeftIn);
tabHost.setAnimation(slideLeftOut);
tabHost.setCurrentTab((tabHost.getCurrentTab()+1)%3);
} else if (eTwo.getX() - eOne.getX() > flingMinDistance && Math.abs(velocityX) > flingMinVelocity) {
tabHost.setAnimation(slideRightIn);
tabHost.setAnimation(slideRightOut);
tabHost.setCurrentTab((tabHost.getCurrentTab()+2)%3);
}
}
catch(Exception e){
}
}
return false;
}
}
//This method alone keeps a touch in the weights from changing tabs, but won't register
//touches on ANY widget on any screen (like text views).
public boolean dispatchTouchEvent(MotionEvent event){
super.dispatchTouchEvent(event);
return gestureDetector.onTouchEvent(event);
}
//This method alone counts touches for swipes anywhere and everywhere.
#Override
public boolean onTouchEvent(MotionEvent event) {
if (gestureDetector.onTouchEvent(event))
return true;
else
return false;
}

Android - How to prevent a user interacting with Gallery

OK, I know this questions sounds weird at first, as GALLERY is designed to be user interactive, but, I like the Gallery functionality, as it suits a lot of my needs. i.e. I can give it a number of pictures, move the whole of them from right to left, or left to right and get them an animate (in my case, zoom) when one of them is selected. So all good.
I just need to do the selection programatically, which I currently have working. I just don't want the user to be able to fling, scroll, select, longpress, etc. by themselves. So no user interaction is required.
So, how can I prevent a user from doing theses things, without writting a gallery function myself (and without chopping a users fingers off!).
Thanks.
Try setting the clickable and focusable properties of your Gallery View to false.
Following worked for me:
Gallery gallery = new Gallery( ctx ) {
#Override
public boolean onTouchEvent(MotionEvent event) {
return true;
}
};
If some interaction is still left you can also try:
Gallery dotList = new Gallery( ctx ) {
#Override
public boolean onTouchEvent(MotionEvent event) {
return true;
}
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return true;
}
};

Android: How to detect when a scroll has ended

I am using the onScroll method of GestureDetector.SimpleOnGestureListener to scroll a large bitmap on a canvas. When the scroll has ended I want to redraw the bitmap in case the user wants to scroll further ... off the edge of the bitmap, but I can't see how to detect when the scroll has ended (the user has lifted his finger from the screen).
e2.getAction() always seems to return the value 2 so that is no help.
e2.getPressure seems to return fairly constant values (around 0.25) until the final onScroll call when the pressure seems to fall to about 0.13. I suppose I could detect this reduction in pressure, but this will be far from foolproof.
There must be a better way: can anyone help, please?
Here is how I solved the problem. Hope this helps.
// declare class member variables
private GestureDetector mGestureDetector;
private OnTouchListener mGestureListener;
private boolean mIsScrolling = false;
public void initGestureDetection() {
// Gesture detection
mGestureDetector = new GestureDetector(new SimpleOnGestureListener() {
#Override
public boolean onDoubleTap(MotionEvent e) {
handleDoubleTap(e);
return true;
}
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
handleSingleTap(e);
return true;
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
// i'm only scrolling along the X axis
mIsScrolling = true;
handleScroll(Math.round((e2.getX() - e1.getX())));
return true;
}
#Override
/**
* Don't know why but we need to intercept this guy and return true so that the other gestures are handled.
* https://code.google.com/p/android/issues/detail?id=8233
*/
public boolean onDown(MotionEvent e) {
Log.d("GestureDetector --> onDown");
return true;
}
});
mGestureListener = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (mGestureDetector.onTouchEvent(event)) {
return true;
}
if(event.getAction() == MotionEvent.ACTION_UP) {
if(mIsScrolling ) {
Log.d("OnTouchListener --> onTouch ACTION_UP");
mIsScrolling = false;
handleScrollFinished();
};
}
return false;
}
};
// attach the OnTouchListener to the image view
mImageView.setOnTouchListener(mGestureListener);
}
You should take a look at http://developer.android.com/reference/android/widget/Scroller.html.
Especially this could be of help (sorted by relevance):
isFinished();
computeScrollOffset();
getFinalY(); getFinalX(); and getCurrY() getCurrX()
getDuration()
This implies that you have to create a Scroller.
If you want to use touching you could also use GestureDetector and define your own canvas scrolling. The following sample is creating a ScrollableImageView and in order to use it, you have to define the measurements of your image. You can define your own scrolling range and after finishing your scrolling the image gets redrawn.
http://www.anddev.org/viewtopic.php?p=31487#31487
Depending on your code you should consider invalidating (int l, int t, int r, int b); for the invalidation.
SimpleOnGestureListener.onFling()
It seems to take place when a scroll ends (i.e. the user lets the finger go), that's what I am using and it works great for me.
Coming back to this after a few months I've now followed a different tack: using a Handler (as in the Android Snake sample) to send a message to the app every 125 milliseconds which prompts it to check whether a Scroll has been started and whether more than 100 milliseconds has elapsed since the last scroll event.
This seems to work pretty well, but if anyone can see any drawbacks or possible improvements I should be grateful to hear of them.
The relevant the code is in the MyView class:
public class MyView extends android.view.View {
...
private long timeCheckInterval = 125; // milliseconds
private long scrollEndInterval = 100;
public long latestScrollEventTime;
public boolean scrollInProgress = false;
public MyView(Context context) {
super(context);
}
private timeCheckHandler mTimeCheckHandler = new timeCheckHandler();
class timeCheckHandler extends Handler{
#Override
public void handleMessage(Message msg) {
long now = System.currentTimeMillis();
if (scrollInProgress && (now>latestScrollEventTime+scrollEndInterval)) {
scrollInProgress = false;
// Scroll has ended, so insert code here
// which calls doDrawing() method
// to redraw bitmap re-centred where scroll ended
[ layout or view ].invalidate();
}
this.sleep(timeCheckInterval);
}
public void sleep(long delayMillis) {
this.removeMessages(0);
sendMessageDelayed(obtainMessage(0), delayMillis);
}
}
}
#Override protected void onDraw(Canvas canvas){
super.onDraw(canvas);
// code to draw large buffer bitmap onto the view's canvas
// positioned to take account of any scroll that is in progress
}
public void doDrawing() {
// code to do detailed (and time-consuming) drawing
// onto large buffer bitmap
// the following instruction resets the Time Check clock
// the clock is first started when
// the main activity calls this method when the app starts
mTimeCheckHandler.sleep(timeCheckInterval);
}
// rest of MyView class
}
and in the MyGestureDetector class
public class MyGestureDetector extends SimpleOnGestureListener {
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
[MyView].scrollInProgress = true;
long now = System.currentTimeMillis();
[MyView].latestScrollEventTime =now;
[MyView].scrollX += (int) distanceX;
[MyView].scrollY += (int) distanceY;
// the next instruction causes the View's onDraw method to be called
// which plots the buffer bitmap onto the screen
// shifted to take account of the scroll
[MyView].invalidate();
}
// rest of MyGestureDetector class
}
This is what worked for me.
I've enriched the existing GestureDetector.OnGestureListener with onFingerUp() method. This listener does everything as the built-in GestureDetector and it can also listen to the finger up event (it's not onFling() as this is called only when the finger is lifted up along with a quick swipe action).
import android.content.Context;
import android.os.Handler;
import android.view.GestureDetector;
import android.view.MotionEvent;
public class FingerUpGestureDetector extends GestureDetector {
FingerUpGestureDetector.OnGestureListener fListener;
public FingerUpGestureDetector(Context context, OnGestureListener listener) {
super(context, listener);
fListener = listener;
}
public FingerUpGestureDetector(Context context, GestureDetector.OnGestureListener listener, OnGestureListener fListener) {
super(context, listener);
this.fListener = fListener;
}
public FingerUpGestureDetector(Context context, GestureDetector.OnGestureListener listener, Handler handler, OnGestureListener fListener) {
super(context, listener, handler);
this.fListener = fListener;
}
public FingerUpGestureDetector(Context context, GestureDetector.OnGestureListener listener, Handler handler, boolean unused, OnGestureListener fListener) {
super(context, listener, handler, unused);
this.fListener = fListener;
}
public interface OnGestureListener extends GestureDetector.OnGestureListener {
boolean onFingerUp(MotionEvent e);
}
public static class SimpleOnGestureListener extends GestureDetector.SimpleOnGestureListener implements FingerUpGestureDetector.OnGestureListener {
#Override
public boolean onFingerUp(MotionEvent e) {
return false;
}
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
if (super.onTouchEvent(ev)) return true;
if (ev.getAction() == MotionEvent.ACTION_UP) {
return fListener.onFingerUp(ev);
}
return false;
}
}
I think this will work as you need
protected class SnappingGestureDetectorListener extends SimpleOnGestureListener{
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY){
boolean result = super.onScroll(e1, e2, distanceX, distanceY);
if(!result){
//Do what you need to do when the scrolling stop here
}
return result;
}
}
I am sure it is too late for you, however, it seems I have found the right solution to your original question and not necessarily the intention.
If you are using Scroller/OverScroller Object for scrolling you should check the return value from the following function.
public boolean computeScrollOffset()
I was looking into this same issue. I saw Akos Cz's answer to your question. I created something similar, but with my version, I noticed that it only worked for a regular scroll - meaning one that doesn't generate a fling. But if a fling did get generated - regardless if I processed a fling or not, then it did NOT detect the "ACTION_UP" in "onTouchEvent". Now maybe this was just something with my implementation, but if it was I couldn't figure out why.
After further investigation, I noticed that during a fling, the "ACTION_UP" was passed into "onFling" in "e2" every time. So I figured that must be why it wasn't being handled in "onTouchEvent" in those instances.
To make it work for me I only had to call a method to handle the "ACTION_UP" in "onFling" and then it worked for both types of scrolling. Below are the exact steps I took to implement my app:
-initialized a "gestureScrolling" boolean to "false" in a constructor.
-I set it to "true" in "onScroll"
-created a method to handle the "ACTION_UP" event. Inside that event, I reset "gestureSCrolling" to false and then did the rest of the processing I needed to do.
-in "onTouchEvent", if an "ACTION_UP" was detected and "gestureScrolling" = true, then I called my method to handle "ACTION_UP"
-And the part that I did that was different was: I also called my method to handle "ACTION_UP" inside of "onFling".
I haven't done this myself but looking at onTouch() you always get a sequence 0<2>1, so the end has to be a 1 for finger lift.
I don't know Android, but looking at the documentation it seems Rob is right: Android ACTION_UP constant Try checking for ACTION_UP from getAction()?
Edit: What does e1.getAction() show? Does it ever return ACTION_UP? The documentation says it holds the initial down event, so maybe it'll also notify when the pointer is up
Edit: Only two more things I can think of. Are you returning false at any point? That may prevent ACTION_UP
The only other thing I'd try is to have a seperate event, maybe onDown, and set a flag within onScroll such as isScrolling. When ACTION_UP is given to onDown and isScrolling is set then you could do whatever you want and reset isScrolling to false. That is, assuming onDown gets called along with onScroll, and getAction will return ACTION_UP during onDown
i have not tried / used this but an idea for an approach:
stop / interrupt redrawing canvas on EVERY scroll event wait 1s and then start redrawing canvas on EVERY scroll.
this will lead to performing the redraw only at scroll end as only the last scroll will actually be uninterrupted for the redraw to complete.
hope this idea helps you :)
Extract from the onScroll event from GestureListener API: link text
public abstract boolean onScroll
(MotionEvent e1, MotionEvent e2, float
distanceX, float distanceY) Since: API
Level 1
Returns
* true if the event is consumed, else false
Perhaps once the event has been consumed, the action is finished and the user has taken their finger off the screen or at the least finished this onScroll action
You can then use this in an IF statement to scan for == true and then commence with the next action.
If you're using SimpleGestureDetector to handle your scroll events, you can do this
fun handleTouchEvents(event: MotionEvent): Boolean {
if(event.action == ACTION_UP) yourListener.onScrollEnd()
return gestureDetector.onTouchEvent(event)
}
My attempt at adding additional functionality to the gesture detector. Hope it helps someone put his time to better use... gist

Categories

Resources