1
我正在嘗試將投擲手勢添加到imageview。 Im使用此代碼將投擲手勢添加到ImageView
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;
}
}
}
但它只是不起作用。日誌說nullpointerexception,它是指這條線imageView.setOnTouchListener(new OnTouchListener() {
我的錯誤在哪裏?我錯過了什麼嗎?
感謝之前實際獲得的ImageView
setContentView(R.layout.yourlayout)
在你之前的onCreate返回null,因爲ü沒有的setContentView():d 的事情是,我之前添加的這段代碼setcontentview,所以我只是把它移到頂端,現在它工作:) – Raz 2013-02-16 14:52:54