在布局文件中添加HorizontalScrollView或ViewPager组件。
监听用户的手势事件,可以使用GestureDetector类。在onTouchEvent方法中创建GestureDetector对象,并重写onFling方法。
GestureDetector mGestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() { @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (e1.getX() < e2.getX()) { // 手势向右滑动 } else if (e1.getX() > e2.getX()) { // 手势向左滑动 } return super.onFling(e1, e2, velocityX, velocityY); } });
@Override public boolean onTouchEvent(MotionEvent event) { mGestureDetector.onTouchEvent(event); return super.onTouchEvent(event); }
示例代码:
public class MainActivity extends AppCompatActivity {
private GestureDetector mGestureDetector;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HorizontalScrollView horizontalScrollView = findViewById(R.id.horizontal_scroll_view);
mGestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (e1.getX() < e2.getX()) {
// 手势向右滑动
horizontalScrollView.scrollTo(0, 0);
} else if (e1.getX() > e2.getX()) {
// 手势向左滑动
horizontalScrollView.scrollTo(horizontalScrollView.getWidth(), 0);
}
return super.onFling(e1, e2, velocityX, velocityY);
}
});
horizontalScrollView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {