onfling() not being called for some reason
Asked Answered
P

2

13

I'm trying to implement gesture in my app and for some reason the the onfling() is not being called. I tried reading numerous posts regarding this and tried fixing my code but it's not working . The below is my code. Please have a look:

public class MainMenuSlider extends Activity implements OnClickListener{

protected MyGestureListener myGestureListener;

private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;

private ViewFlipper vf;
private Animation animFlipInNext,animFlipOutNext, animFlipInPrevious, animFlipOutPrevious;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.mainmenuslider);
    myGestureListener = new MyGestureListener(this);

    //vf for viewflipper
    vf=(ViewFlipper)findViewById(R.id.ViewFlipper01);
    animFlipInNext = AnimationUtils.loadAnimation(this, R.anim.flipinnext);
    animFlipOutNext = AnimationUtils.loadAnimation(this, R.anim.flipoutnext);
    animFlipInPrevious = AnimationUtils.loadAnimation(this, R.anim.flipinprevious);
    animFlipOutPrevious = AnimationUtils.loadAnimation(this, R.anim.flipoutprevious);

    imageone = (ImageView) findViewById(R.id.imageone);
    imagetwo = (ImageView) findViewById(R.id.imagetwo);
    imageone.setOnClickListener(myGestureListener);
    imagetwo.setOnClickListener(myGestureListener);


} 


class MyGestureListener extends SimpleOnGestureListener implements OnTouchListener
    {
        Context context;
        GestureDetector gDetector;

    public MyGestureListener()
    {
        super();
    }

    public GestureDetector getDetector()
    {
        return gDetector;
    } 

    public MyGestureListener(Context context) 
    {
        this(context, null);
    }

    public MyGestureListener(Context context, GestureDetector gDetector) 
    {

        if(gDetector == null)
            gDetector = new GestureDetector(context, this);

        this.context = context;
        this.gDetector = gDetector;
    }

    public boolean onDown(MotionEvent event) 
    {
        return true;
    }


    @Override
    public boolean onFling(MotionEvent e1,MotionEvent e2,float velocityX,float velocityY)
    {
        try {
            if(e1.getX() > e2.getX() && Math.abs(e1.getX() - e2.getX()) > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                vf.setInAnimation(animFlipInPrevious);
                vf.setOutAnimation(animFlipOutPrevious);
                vf.showPrevious();
            }else if (e1.getX() < e2.getX() && e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                vf.setInAnimation(animFlipInNext);
                vf.setOutAnimation(animFlipOutNext);
                vf.showNext();
            }
        } catch (Exception e) {
            // nothing
        }
        return true;

    }

    @Override
    public boolean onSingleTapConfirmed(MotionEvent e) 
    {

        return super.onSingleTapConfirmed(e);
    }

    public boolean onTouch(View v, MotionEvent event) 
    {

        // Within the MyGestureListener class you can now manage the event.getAction() codes.

        // Note that we are now calling the gesture Detectors onTouchEvent. And given we've set this class as the GestureDetectors listener 
        // the onFling, onSingleTap etc methods will be executed.
        return gDetector.onTouchEvent(event);
    }


    public void onClick(View v) 
    {
        if (v == imageone)
        {
            Intent j = new Intent(getApplicationContext(), MainActivity.class);
            j.putExtra("slideindex", 0);
            startActivity(j);
        }

        if (v == imagetwo)
        {
            Intent j = new Intent(getApplicationContext(), MainActivity.class);
            j.putExtra("slideindex", 1);
            startActivity(j);
        }
    }

    public boolean onScroll(MotionEvent e1,MotionEvent e2,float distanceX,float distanceY)
    {
        return true;
    }


  }
}

EDIT: Here is the mainmenuslider XML file content as requested

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical"
              android:background="#291E3D" >

            <ScrollView android:layout_width="fill_parent"
                          android:layout_height="fill_parent"
                          android:orientation="vertical" >

                    <LinearLayout android:layout_width="fill_parent"
                                  android:layout_height="fill_parent"
                                  android:gravity="center"
                                  android:orientation="vertical" >

                            <ViewFlipper android:id="@+id/ViewFlipper01"
                                                 android:layout_height="wrap_content" 
                                                 android:layout_width="fill_parent"
                                                 android:gravity="center" >

                                    <!-- adding views to ViewFlipper --> 

                                            <!-- First Slide --> 
                                            <LinearLayout android:layout_width="fill_parent"
                                                          android:layout_height="fill_parent"
                                                          android:gravity="center"
                                                          android:orientation="vertical" >


                                                    <TextView android:id="@+id/title1"
                                                              android:text="title1" 
                                                              android:textColor="#ffffff"
                                                              android:layout_width="fill_parent" 
                                                              android:layout_height="wrap_content" 
                                                              android:gravity="center"
                                                              android:layout_marginBottom="3dip"
                                                              android:textSize="25dip"/>


                                                    <ImageView android:id="@+id/imageone" 
                                                               android:clickable="true"
                                                               android:layout_width="wrap_content" 
                                                               android:layout_height="wrap_content" 
                                                               android:src="@drawable/splash_screen">
                                                    </ImageView>


                                            </LinearLayout>

                                            <!-- Second Slide --> 
                                            <LinearLayout android:layout_width="fill_parent"
                                                          android:layout_height="fill_parent"
                                                          android:gravity="center"
                                                          android:orientation="vertical" >


                                                    <TextView android:id="@+id/title2"
                                                              android:text="title2" 
                                                              android:textColor="#ffffff"
                                                              android:layout_width="fill_parent" 
                                                              android:layout_height="wrap_content"
                                                              android:gravity="center"
                                                              android:layout_marginBottom="3dip"
                                                              android:textSize="25dip" />


                                                    <ImageView android:id="@+id/imagetwo"
                                                               android:clickable="true"
                                                               android:layout_width="wrap_content" 
                                                               android:layout_height="wrap_content" 
                                                               android:src="@drawable/sunnahsplash">
                                                    </ImageView>


                                            </LinearLayout>



                                    </ViewFlipper>





                            <!-- footer -->
                            <LinearLayout android:id="@+id/LinearLayout03"
                                          android:layout_height="wrap_content" 
                                          android:layout_width="wrap_content" 
                                          android:orientation="horizontal" 
                                          android:layout_gravity="center"
                                          android:layout_marginTop="10dip">

                                            <Button android:id="@+id/Button02" 
                                                    android:layout_height="wrap_content" 
                                                    android:text="&lt;Previous" 
                                                    android:textSize="18dip"
                                                    android:layout_width="wrap_content" 
                                                    android:layout_gravity="center"
                                                    android:layout_marginRight="15dip"
                                                    android:padding="5dp"
                                                    android:background="@drawable/background_button_slider"></Button>
                                            <Button android:id="@+id/Select" 
                                                    android:text=" Select " 
                                                    android:textSize="18dip"
                                                    android:layout_height="match_parent" 
                                                    android:layout_width="wrap_content" 
                                                    android:layout_gravity="center"
                                                    android:padding="5dp"
                                                    android:background="@drawable/background_button_slider"></Button>
                                            <Button android:id="@+id/Button01" 
                                                    android:text=" Next&gt;" 
                                                    android:textSize="18dip"
                                                    android:layout_height="match_parent" 
                                                    android:layout_width="wrap_content" 
                                                    android:layout_gravity="center"
                                                    android:layout_marginLeft="15dip"
                                                    android:padding="5dp"
                                                    android:background="@drawable/background_button_slider"></Button>
                            </LinearLayout>

                    </LinearLayout>

            </ScrollView>


</LinearLayout>
Periodic answered 24/7, 2013 at 9:49 Comment(3)
can you please post your layout xml file?Quoin
why do you seryp gesture listener for imageone, imagetwo etc?Animalist
@AbhishekAgarwal : I have edited the main post and added the XML. Please check it. Thank you.Periodic
Q
9

According to me the fling is not working because of the scroll view.... Add this code into your MainMenuSlider class.

   GestureDetector gestureDetector
    = new GestureDetector(myGestureListener);

    @Override
    public boolean dispatchTouchEvent(MotionEvent e)
    {
        super.dispatchTouchEvent(e);
        return gestureDetector.onTouchEvent(e);
    }

I have edited your code of class as

      public class MainMenuSlider extends Activity implements OnClickListener{



 private static final int SWIPE_MIN_DISTANCE = 120;
 private static final int SWIPE_MAX_OFF_PATH = 250;
 private static final int SWIPE_THRESHOLD_VELOCITY = 200;

private ViewFlipper vf;
private Animation animFlipInNext,animFlipOutNext, animFlipInPrevious, a   nimFlipOutPrevious;

private ImageView imageone;

private ImageView imagetwo;

 public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main_menu_slider);
//myGestureListener = new MyGestureListener(this);

//vf for viewflipper
vf=(ViewFlipper)findViewById(R.id.ViewFlipper01);
animFlipInNext = AnimationUtils.loadAnimation(this, R.anim.flipinnext);
animFlipOutNext = AnimationUtils.loadAnimation(this, R.anim.flipoutnext);
animFlipInPrevious = AnimationUtils.loadAnimation(this, R.anim.flipinprevious);
animFlipOutPrevious = AnimationUtils.loadAnimation(this, R.anim.flipoutprevious);

imageone = (ImageView) findViewById(R.id.imageone);
imagetwo = (ImageView) findViewById(R.id.imagetwo);
imageone.setOnClickListener(myGestureListener);
imagetwo.setOnClickListener(myGestureListener);


 } 

@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
return gestureDetector.onTouchEvent(event);
  }

 SimpleOnGestureListener simpleOnGestureListener 
 = new SimpleOnGestureListener(){

@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
        float velocityY) {

    float sensitvity = 50;
    if((e1.getX() - e2.getX()) > sensitvity){
        vf.showPrevious();
    }else if((e2.getX() - e1.getX()) > sensitvity){
        vf.showNext();
    }

    return true;
}

};

 GestureDetector gestureDetector
 = new GestureDetector(simpleOnGestureListener);
 @Override
 public boolean dispatchTouchEvent(MotionEvent e)
 {
super.dispatchTouchEvent(e);
return gestureDetector.onTouchEvent(e);
}
  public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Hello",Toast.LENGTH_SHORT
        ).show();
    }

This code is working properly..

Quoin answered 24/7, 2013 at 11:52 Comment(8)
It's giving me a 'Cannot be resolved' error on gestureDetector . I think here gestureDetector seems to be a GestureDetector type object but don't have any in my main class. Rather, there is a GestureDetector in my "MyGestureListener" class (if you check the code)Periodic
GestureDetector gestureDetector = new GestureDetector(new MyGestureListener());Quoin
Ok, did that.. but unfortunately it's not working. Rather, my app crashed and in the log the error reads "OnGestureListener must not be null"Periodic
Sorry bro. Same result. App crashes with "OnGestureListener must not be null" error.Periodic
I have updated the answer and you can add your views click event later and the viewflipper is working now.Quoin
Ok, I will try it and get back to you soon about the result. Thanks a lot for your time.Periodic
Ok, big update! I tried your code and the fling is working but now there is a new issue. There seems to be a 'clash' between my OnFling and OnClick of my ImageView. Basically, what's happening is that whenever I fling, the onclick() is also getting fired. Well to be precise, the reason I strcutured my original code (the way it was) was to overcome this issue. I got this idea from the answer of this post ---> #4184882 . Please have a look.Periodic
Right after closing OnCreate().Periodic
A
1

To capture touch events other than clicks, you need to use a custom gesture detector, perhaps a subclass of your activity such as this:

private class CustomGestureListener extends GestureDetector.SimpleOnGestureListener {
    @Override       
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        boolean usedThisFling = false;

        // Is it horizontal?
        if (Math.abs(velocityX) >= 2.0*Math.abs(velocityY)) {
            if (velocityX < 0.0)     leftSwipeActions();
            else                     rightSwipeActions();
            usedThisFling = true;
        }
        return usedThisFling;
    }

Then, it needs to be instantiated and set up to be used in you onCreate() method:

// Create it.
final GestureDetector myGestureListener = new GestureDetector(getApplicationContext(), new CustomGestureListener());

// Set it up for use:
imageone.setOnTouchListener(new OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {
        return myGestureListener.onTouchEvent(event);
    }
});

// And put an onClick method it to force it to work (this shouldn't be necessary but
// it seems like sometimes it is)
imageone.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
    }
});
Avalon answered 24/7, 2013 at 13:4 Comment(9)
But what is the relation between this and the working of OnFling() ?Periodic
I will try your solution and let you knowPeriodic
Thank you so much, in my case the onFling was not triggered because I didn't set a OnClickListener. I have been stuck for hours, everything is working fine now :DExorable
Why isn't OnFling triggered without an OnClickListener? I had the same issue.Micaelamicah
@Le-royStaines I don’t know. I’ve just out in the answer what I have found to be true in practice.Avalon
@NeilTownsend it's a pain because as soon as I put the OnClickListener on the target, it stops click events passing through to the layer below, or the children inside.Micaelamicah
@Le-royStaines I think that that is solvable, but I haven’t looked into it recently. I would suggest search on how to pass I click events onto children / parents and see what options there are.Avalon
Yeah so far I've not managed to get that to work. Thanks for your help!Micaelamicah
@Le-royStaines I would suggest asking this as a separate question, as it may trigger someone else who has solved your specific problem to answer ....Avalon

© 2022 - 2024 — McMap. All rights reserved.