1

I'm trying to add fling gesture to an imageview. Im using this code

public class MyActivity extends Activity { private void onCreate() { final GestureDetector gdt = new GestureDetector(new GestureListener()); final ImageView imageView = (ImageView) findViewById(R.id.image_view); imageView.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(final View view, final MotionEvent event) { gdt.onTouchEvent(event); return true; } }); } private static final int SWIPE_MIN_DISTANCE = 120; private static final int SWIPE_THRESHOLD_VELOCITY = 200; private class GestureListener extends SimpleOnGestureListener { @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { return false; // Right to left } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { return false; // Left to right } if(e1.getY() - e2.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) { return false; // Bottom to top } else if (e2.getY() - e1.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) { return false; // Top to bottom } return false; } } } 

But it just doesn't work. The log says nullpointerexception and it refers to this line imageView.setOnTouchListener(new OnTouchListener() {

Where is my mistake? Am I missing something?

1 Answer 1

1

Your imageView returning null because U haven't setContentView() before actually getting the imageview

setContentView(R.layout.yourlayout) in your onCreate before getting the imageview

Sign up to request clarification or add additional context in comments.

1 Comment

thanks :D the thing is that i added this code before the setcontentview so i just moved it to the top and now it works :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.