8

我是为 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 消息作为 Right Swipe。但图像不动。我该如何实施?请帮助我提供示例代码/链接。

4

2 回答 2

7

我找到了一个简单的解决方案,如下所示:

对于向右滑动(向右):

btnSwipe.setTranslationX(e2.getX());

对于向左滑动(向左)"

btnSwipe.setTranslation(e1.getX());

现在,ImageView 正在水平地从右到左和从左到右转换。但这适用于 Android APILevel 11 及更高版本。

于 2013-11-10T07:42:35.997 回答
3

您需要使用 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

这是有关图像滑块的优秀教程的链接

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

于 2013-11-09T13:37:56.727 回答