I have a RelativeLayout that contains many child views with various touch events. I want to get notified when the user swipes anywhere on the parent RelativeLayout so I can update some UI while still letting the child views handle their own touch/drag events. What is the standard way of accomplishing this for Android?
I was thinking that I could put an overlay over all the views and have it detect swipe gestures and if it wasn't a swipe I could pass the touch event on to other views in the hierarchy. It doesn't seem like Android supports that sort of touch detection and once one view decides to see if a event is a certain gesture no other views will be able to see the events.
A swipe gesture consists of three touch events: ACTION_DOWN, ACTION_MOVE and ACTION_UP. You need to record all three events and then see if it was a swipe or not. If it was not a swipe then we would need to pass those events to other child views to see if it meets their criteria for the gesture they are looking for. If it is a swipe we would want to block the events from being sent to the child view. Just not sure if this is actually possible.
Update
Using the ideas of the users in the answers section I was able to write a layout that met my specification. This RelativeLayout just handles right and left swipes but could be added to to handle more directions. OnSwipeListener is just an interface with two methods void swipedLeft() and void swipedRight().
public class SwipeRelativeLayout extends RelativeLayout {
public OnSwipeListener mSwipeListener = null;
private static final int SWIPE_DISTANCE_THRESHOLD = 100;
private float mStartX = 0;
private float mStartY = 0;
private float mEndX = 0;
private float mEndY = 0;
public SwipeRelativeLayout(Context context) {
super(context);
}
public SwipeRelativeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SwipeRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public SwipeRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
boolean handled = onTouchEvent(event);
if (event.getAction() == MotionEvent.ACTION_UP) return handled;
return false;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
mStartX = event.getRawX();
mStartY = event.getRawY();
break;
}
case MotionEvent.ACTION_MOVE: {
float distanceX = event.getRawX() - mStartX;
float distanceY = event.getRawY() - mStartY;
if (Math.abs(distanceX) > Math.abs(distanceY) && Math.abs(distanceX) > SWIPE_DISTANCE_THRESHOLD) {
if (distanceX > 0) {
if (mSwipeListener != null) mSwipeListener.swipedRight();
} else {
if (mSwipeListener != null) mSwipeListener.swipedLeft();
}
return true;
}
return false;
}
}
return true;
}
}
When a touch event occurs it is first passed to the parent layout view and passed on to child view via onInterceptTouchEvent returning true or false. You want to override and intercept the touch events on the parent RelativeLayout and determine if you have seen a swipe gesture or not. If you have seen a swipe you want to return that you have handled it. In this case ACTION_UP is the end of a possible swipe and if your onTouchEvent handled the event then you can return true and the views below it will not get the finishing event and thus ignore their gestures.
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
boolean handled = onTouchEvent(event);
if (event.getAction() == MotionEvent.ACTION_UP) return handled;
return false;
}
Related
**All of the information below is with regards to the icons illustrated on the right side of the gif.
I have created a simple toolbar that has a button that changes the image based on the position of the fragment. Everything works fine, however, I can't seem to get the fading correctly. I want the images to fade nicely as the fragment changes. Right now, going from the center (position 1) to the left (position 0) has a nice fade. The icon changes from an equalizer to a chat icon. However, going back from left (position 0) to center (position 1) makes the image pop into frame (not a fade). Additionally the same is observed going from center (position 1) to the right (position 2) and vice versa. There is no fading in this case either.
I believe the issue is with the if else statements and the setAlpha.
Position 0 (Left side)
Position 1 (Center)
Position 2 (Right side)
Gif Demo (What current code does):
https://imgur.com/a/vNEJZAJ
Code:
public class TopVariableFunctionalityButtonView extends FrameLayout implements ViewPager.OnPageChangeListener {
// Initialize content
private ImageView mVariableFunctionalityButtonImageView;
private ImageView mVariableFunctionalityButtonBackgroundImageView;
private ArgbEvaluator mArgbEvaluator;
// Initialize color change
private int mCenterVariableFunctionalityButtonColor;
private int mSideVariableFunctionalityButtonColor;
private int mCenterVariableFunctionalityButtonBackgroundColor;
private int mSideVariableFunctionalityButtonBackgroundColor;
public TopVariableFunctionalityButtonView(#NonNull Context context) {
this(context, null);
}
public TopVariableFunctionalityButtonView(#NonNull Context context, #Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public TopVariableFunctionalityButtonView(#NonNull Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public void setUpWithViewPager(ViewPager viewPager) {
viewPager.addOnPageChangeListener(this);
mVariableFunctionalityButtonImageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (viewPager.getCurrentItem() == 2)
HomeActivity.openSettings(getContext());
}
});
}
private void init() {
LayoutInflater.from(getContext()).inflate(R.layout.view_top_variable_functionality_button, this, true);
// Initialize top variable functionality button image
mVariableFunctionalityButtonImageView = findViewById(R.id.view_top_variable_functionality_button_image_view);
// Initialize top variable functionality button image background
mVariableFunctionalityButtonBackgroundImageView = findViewById(R.id.view_top_variable_functionality_button_background_image_view);
// Set start color and end color for button icons
mCenterVariableFunctionalityButtonColor = ContextCompat.getColor(getContext(), R.color.white);
mSideVariableFunctionalityButtonColor = ContextCompat.getColor(getContext(), R.color.iconColor);
mCenterVariableFunctionalityButtonBackgroundColor = ContextCompat.getColor(getContext(), R.color.transparentSearch);
mSideVariableFunctionalityButtonBackgroundColor = ContextCompat.getColor(getContext(), R.color.secondaryColor);
// Evaluate the difference between colors
mArgbEvaluator = new ArgbEvaluator();
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (position == 0) {
// Change color of icons based on view
setColor(1 - positionOffset);
// Change variable button image
mVariableFunctionalityButtonImageView.setAlpha(1 - positionOffset);
mVariableFunctionalityButtonImageView.setBackgroundResource(R.drawable.ic_chat);
} else if (position == 1) {
// Change color of icons based on view
setColor(positionOffset + 1);
// Change variable button image
mVariableFunctionalityButtonImageView.setAlpha(positionOffset + 1);
mVariableFunctionalityButtonImageView.setBackgroundResource(R.drawable.ic_equalizer);
} else if (position == 2) {
// Change color of icons based on view
setColor(positionOffset + 1);
// Change variable button image
mVariableFunctionalityButtonImageView.setAlpha(positionOffset + 1);
mVariableFunctionalityButtonImageView.setBackgroundResource(R.drawable.ic_settings);
}
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
private void setColor(float fractionFromCenter) {
int variableFunctionalityButtonColor = (int) mArgbEvaluator.evaluate(fractionFromCenter,
mCenterVariableFunctionalityButtonColor, mSideVariableFunctionalityButtonColor);
int variableFunctionalityButtonBackgroundColor = (int) mArgbEvaluator.evaluate(fractionFromCenter,
mCenterVariableFunctionalityButtonBackgroundColor, mSideVariableFunctionalityButtonBackgroundColor);
mVariableFunctionalityButtonImageView.setColorFilter(variableFunctionalityButtonColor);
mVariableFunctionalityButtonBackgroundImageView.setColorFilter(variableFunctionalityButtonBackgroundColor);
}
}
I have an android app with two seekbars, and I've set them up so that the app doesn't respond unless both of them are pressed. My problem is that when they are both pressed down, the method onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) starts continuously running in an infinite loop. This happens even though I am holding my fingers completely still on the bars (which means that the progress is not changing on either of the bars, and therefore the onProgressChanged method shouldn't be being called). Does anyone have any insights as to why this could be happening?
Here is some relevant code:
void setupLRSpeedBars(final int UIID, final Bool bar1, final Bool bar2) {
SeekBar sb = (SeekBar) findViewById(UIID);
sb.setProgress(9);
sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (bar1.isTrue()) {
progress -= 9;
transmit((UIID == R.id.leftSpeedBar ? "L" : "R") +
(progress >= 0 ? "+" : "") +
Integer.toString(progress));
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
bar2.set(true);
}
public void onStopTrackingTouch(SeekBar seekBar) {
bar2.set(false);
seekBar.setProgress(9);
//transmit((UIID == R.id.leftSpeedBar ? "L" : "R") + "+0");
transmit("s");
}
});
}
Also note that I've used a custom Bool class instead of a primitive boolean, in order for me to get around the restriction that all variables outside of the OnSeekBarChangeListener be marked final. (I need to send information between the onSeekBarChangeListeners in order to work out whether the user is holding their fingers down on both seekbars at the same time)
I have a hunch that this might be the cause of my problems, but I don't see how.
class Bool {
private boolean bool;
public Bool () {}
public Bool(boolean bool) { this.bool = bool; }
public void set (boolean bool) { this.bool = bool; }
public boolean get () { return bool; }
public boolean isTrue () { return bool; }
}
EDIT:
I'll also note that I'm using a custom, vertical seekbar. Here is the code:
package android.widget;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;
public class VerticalSeekBar extends SeekBar {
private OnSeekBarChangeListener myListener;
public VerticalSeekBar(Context context) {
super(context);
}
public VerticalSeekBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public VerticalSeekBar(Context context, AttributeSet attrs) {
super(context, attrs);
}
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(h, w, oldh, oldw);
}
#Override
protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(heightMeasureSpec, widthMeasureSpec);
setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth());
}
#Override
public void setOnSeekBarChangeListener(OnSeekBarChangeListener mListener){
this.myListener = mListener;
}
#Override
public synchronized void setProgress(int progress){
super.setProgress(progress);
onSizeChanged(getWidth(), getHeight(), 0, 0);
}
protected void onDraw(Canvas c) {
c.rotate(-90);
c.translate(-getHeight(), 0);
super.onDraw(c);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (!isEnabled()) {
return false;
}
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if(myListener!=null)
myListener.onStartTrackingTouch(this);
break;
case MotionEvent.ACTION_MOVE:
setProgress(getMax() - (int) (getMax() * event.getY() / getHeight()));
onSizeChanged(getWidth(), getHeight(), 0, 0);
myListener.onProgressChanged(this, getMax() - (int) (getMax() * event.getY() / getHeight()), true);
break;
case MotionEvent.ACTION_UP:
myListener.onStopTrackingTouch(this);
break;
case MotionEvent.ACTION_CANCEL:
break;
}
return true;
}
}
I think that the problem is in the onTouchEvent implementation of your VerticalSeekBar because you are processing every MotionEvent.ACTION_MOVE received.
From the documentation:
A new onTouchEvent() is triggered with an ACTION_MOVE event whenever the current touch contact position, pressure, or size changes. As described in Detecting Common Gestures, all of these events are recorded in the MotionEvent parameter of onTouchEvent().
Because finger-based touch isn't always the most precise form of interaction, detecting touch events is often based more on movement than on simple contact. To help apps distinguish between movement-based gestures (such as a swipe) and non-movement gestures (such as a single tap), Android includes the notion of "touch slop." Touch slop refers to the distance in pixels a user's touch can wander before the gesture is interpreted as a movement-based gesture. For more discussion of this topic, see Managing Touch Events in a ViewGroup.
That is, you think that your fingers are completely still but your seek bars are receiving ACTION_MOVE events.
In your case, the "touch slop" approximation is now a good idea because the calculated touch slop is huge for your purposes, as touch slop is defined as:
"Touch slop" refers to the distance in pixels a user's touch can wander before the gesture is interpreted as scrolling. Touch slop is typically used to prevent accidental scrolling when the user is performing some other touch operation, such as touching on-screen elements.
To solve your problem you can calculate the distance between the last managed position and the current one to trigger your onProgressChanged:
private static final float MOVE_PRECISION = 5; // You may want to tune this parameter
private float lastY;
// ...
#Override
public boolean onTouchEvent(MotionEvent event) {
if (!isEnabled()) {
return false;
}
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
lastY = event.getY();
if (myListener != null)
myListener.onStartTrackingTouch(this);
break;
case MotionEvent.ACTION_MOVE:
if (calculateDistanceY(event) > MOVE_PRECISION) {
setProgress(getMax() - (int) (getMax() * event.getY() / getHeight()));
onSizeChanged(getWidth(), getHeight(), 0, 0);
myListener.onProgressChanged(this, getMax() - (int) (getMax() * event.getY() / getHeight()), true);
lastY = event.getY();
}
break;
case MotionEvent.ACTION_UP:
myListener.onStopTrackingTouch(this);
break;
case MotionEvent.ACTION_CANCEL:
break;
}
return true;
}
private float calculateDistanceY (MotionEvent event) {
return Math.abs(event.getY() - lastY);
}
I have GridViewPager with 2 rows and 3 columns. As its default behavior If u swipe down on any page it will navigate to first page of next row. But i want to override that behaviorand stop Swipe Down on first row second and third columns.
I have tried putting 2 row one column GridViewPager and putting a ViewPager for first cell as well as using 1 row 3 column GridViewPager with putting Another 1 column 2 row GridViewPager in first cell. Both has similar scrolling problems.Bellow code is the custom GridViewPager I used to change scrolling behavior.
GridViewPager should be able swipe only as following picture.Swipe Example Image
public class GridViewPagerCustom extends GridViewPager {
private GestureDetector mGestureDetector;
private int px = 0;
private int py = 0;
public int getPy() {
return py;
}
public void setPy(int py) {
this.py = py;
}
public int getPx() {
return selectedPage;
}
public void setPx(int px) {
this.px = px;
}
public GridViewPagerCustom(Context context, AttributeSet attrs) {
super(context, attrs);
mGestureDetector = new GestureDetector(context, new YScrollDetector());
setFadingEdgeLength(0);
}
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return super.onInterceptTouchEvent(ev) && mGestureDetector.onTouchEvent(ev);
}
// Return false if we're scrolling in the x direction
class YScrollDetector extends GestureDetector.SimpleOnGestureListener {
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return (getPx() == 0 && getPy() == 0) ? Math.abs(distanceY) > Math.abs(distanceX) : false;
}
}
}
You should be able to control that by overriding canScrollVertically(int direction); I haven't tried that but sounds like the right place. That said, please be careful about changing that behavior since it will then be different from other apps that use this component and users of your app may get confused assuming that there are no other rows, etc.
I am using Flipper as parent and Listview as child. My problem here is the flipping and clicking of item in listview. When I flip to next page (by dragging from right to left) I accidentally click a list Item.
How will I disable the onClick of listview when I already made a gesture for flipping?
Code:
Flipper Ontouch:
public boolean dispatchTouchEvent(MotionEvent touchevent) {
super.dispatchTouchEvent(touchevent);
switch (touchevent.getAction()) {
case MotionEvent.ACTION_DOWN: {
lastX = touchevent.getX();
break;
}
case MotionEvent.ACTION_UP: {
float currentX = touchevent.getX();
if (lastX - 100 > currentX) {
if (result_pageNum < max_pageNum) {
result_pageNum++;
if (vf.getDisplayedChild() == 0) {
listView[1].setClickable(false);
setListView(1);
} else {
listView[0].setClickable(false);
setListView(0);
}
vf.setInAnimation(this, R.anim.in_from_right);
vf.setOutAnimation(this, R.anim.out_to_left);
vf.showNext();
}
} else if (lastX + 100 < currentX) {
if (result_pageNum > 0) {
result_pageNum--;
if (vf.getDisplayedChild() == 1) {
listView[0].setClickable(false);
setListView(0);
} else {
listView[1].setClickable(false);
setListView(1);
}
vf.setInAnimation(this, R.anim.in_from_left);
vf.setOutAnimation(this, R.anim.out_to_right);
vf.showPrevious();
}
}
break;
}
}
return false;
}
listView onClick:
private void listView_onClick() {
for (int i = 0; i < listView.length; i++) {
listView[i].setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.maketext(this,"Working!",Toast.LENGTH_LONG).show();
}
});
}
}
In your dispatchTouchEvent method, when a fling gesture has been detected (under ACTION_UP event), try returning true as a boolean value rather that returning false every time. When no fling gesture is detected according to your movement calculation, then only return false .
You shouldn't really be using dispatchTouchEvent(MotionEvent) for this purpose.
Instead you should use onInterceptTouchEvent(MotionEvent) and onTouchEvent(MotionEvent).
The relationship between these methods are documented in the methods' Javadoc, but as a summary:
onInterceptTouchEvent(MotionEvent) decides whether a ViewGroup intercepts a user touch events from any of it's child views. For instance, your ViewFlipper decides whether the ListView recieves the events.
onTouchEvent(MotionEvent) is where your ViewFlipper can actually react to it's touch events.
i'm trying to drag and drop a button the problem is that when i use getX() at motion event it works but the button starts to tremble . When i call the method getRawX() it does not tremble but it jumps at least 80px right before i start the drag and drop .
how can i managed that , i'll post my code here:
public class MyButton extends Button {
private final static int START_DRAGGING = 0;
private final static int STOP_DRAGGING = 1;
private int status;
private LinearLayout parentLayout;
public MyButton(Context context) {
super(context);
}
public MyButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// Log.i("teste", "Button width: " + btWidth + ", Height : "+ btHeight);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
status = START_DRAGGING;
Log.i("teste", "Coordenada on ACTION_DOWN: " + (int) event.getRawX());
break;
case MotionEvent.ACTION_UP:
status = STOP_DRAGGING;
Log.i("teste", "Coordenada on ACTION_UP: " + (int) event.getRawX());
break;
case MotionEvent.ACTION_MOVE:
if(status == START_DRAGGING){
parentLayout.setPadding((int)event.getRawX(), 0,0,0);
parentLayout.invalidate();
Log.i("teste", "Coordenada on ACTION_MOVE: " + (int) event.getRawX());
}
break;
}
return true;
}
}
event.getX() returns touch coordinates relative to your view (the button), event.getRawX() returns touch coordinates relative to the display, so I would think the first way is the correct one, if you set the padding of the button, instead of the layout. But you'll still have the "jump" problem because you're supposed to touch the button, not its edge, and the first move will put the edge under your finger.
I would try using a GestureDetector, its OnGestureListener has an onScroll() method that gives you the scrolling distance (it does the job of remembering last position and giving a relative motion), so that you can add that value to the padding, that is, you drag 10px => you add 10px of padding.
code example:
private GestureDetector gd =
new GestureDetector(getContext(), new SimpleOnGestureListener() {
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
setPadding((int)(getPaddingLeft()+distanceX),0,0,0);
}
#Override
public boolean onDown(MotionEvent e) {
return true; // else no event will be handled
}
I would also add some checks to prevent negative or excessive paddings.
I have been working on touching and moving objects too. I started out making something move in a similar way: changing the top and left padding. Pretty quickly, as I added more moveable objects to the screen, things got a bit confusing. I would touch one spot on the screen and something else would start moving. What was going on was there were multiple overlapping views on the screen. Only the top view would receive the touch events.
I found a post that suggested taking a look at the Android Launcher code and seeing how they did drag and drop. I think their approach is really good. You do have to add a ViewGroup to hold your moveable objects, but that works out. The bounds of views match what you see on the screen and you end up with no surprises. Events go to the view you expect.
If it turns out you are going to have more than one moveable object, you might want to take a look at my blog post: "Moving Views In Android". More explanations about the Android Launcher and source code are there.