我是新手,可以为Android应用程序实现Swipe Gesture。我正在尝试使用以下代码从屏幕左侧滑动到右侧:
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消息作为右滑动。但是形象并没有动人。我该如何实现呢?请帮我提供示例代码/链接。
答案 0 :(得分:6)
我找到了一个简单的解决方案如下:
右滑动(朝右):
btnSwipe.setTranslationX(e2.getX());
左滑动(向左)“
btnSwipe.setTranslation(e1.getX());
现在,ImageView正在从右向左和从左向右水平过渡。但这可以从Android API
等级11开始。
答案 1 :(得分: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
以下是有关Image Slider
的优秀教程的链接