簡體   English   中英

Android - 如何在Swipe上移動ImageView

[英]Android - How to move ImageView on Swipe

我是新手,為Android應用程序實現Swipe Gesture。 我正在嘗試使用以下代碼從屏幕的左側向右側滑動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) {
}
}

我正在收到Toast消息作為右鍵滑動。 但是形象並沒有動人。 我該如何實現呢? 請幫我提供示例代碼/鏈接。

我找到了一個簡單的解決方案如下:

右側滑動(朝向右側):

btnSwipe.setTranslationX(e2.getX());

左側滑動(向左)

btnSwipe.setTranslation(e1.getX());

現在,ImageView正在從右向左和從左向右水平過渡。 但這適用於Android API Level 11以上版本。

您需要使用PagerAdapter進行滑動功能。 像這樣的東西:

public class FullScreenImageAdapter extends PagerAdapter {

//Stores all the image paths
private ArrayList<String> _imagePaths;

.........


 @Override
    public Object instantiateItem(ViewGroup container, int position) {
//This method is called each time user swipes the screen
//Write suitable code to display next image on the screen
}

......

}

這是官方文檔的鏈接。

http://developer.android.com/training/animation/screen-slide.html http://developer.android.com/reference/android/support/v4/view/PagerAdapter.html

這是關於Image Slider的優秀教程的鏈接

http://www.androidhive.info/2013/09/android-fullscreen-image-slider-with-swipe-and-pinch-zoom-gestures/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM