我是新來實現Android應用程序的滑動手勢。我試圖從刷卡左一個ImageView的使用下面的代碼在屏幕的右側:Android - 如何移動ImageView在滑動
public class MainActivity extends Activity implements OnClickListener{
private static final int SWIPE_MIN_DISTANCE = 10;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
private GestureDetector gestureDetector;
View.OnTouchListener gestureListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView btnSwipe = (ImageView)findViewById(R.id.imgBtnSwipe);
btnSwipe.setOnClickListener(this);
gestureDetector = new GestureDetector(this, new MyGestureDetector());
gestureListener = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
};
btnSwipe.setOnTouchListener(gestureListener);
}
class MyGestureDetector extends SimpleOnGestureListener {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
try {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
return false;
if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
Toast.makeText(MainActivity.this, "Left Swipe", Toast.LENGTH_SHORT).show();
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
Toast.makeText(MainActivity.this, "Right Swipe", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// nothing
}
return false;
}
}
@Override
public void onClick(View v) {
}
}
我得到吐司消息向右滑動。但形象不動。我怎樣才能實現呢?請幫助我提供示例代碼/鏈接。
第二個「向左滑動」,我想它一定是setTranslationX,對吧? – iversoncru
當我嘗試使用「setTranslation」與視圖(這裏是btnSwipe ImageView),有一個錯誤:「該方法setTranslationX未定義的類型查看」 ImageView的同樣的錯誤。有任何想法嗎? – iversoncru
什麼是您的API級別?如果它小於11,那麼你不會有這個功能。 – Brianide