我正在尝试为水平导航实现 ViewPager,并为垂直导航实现 GestureDetector 的 onFling。ViewPager 没问题,但是 onFling 不行。编码:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_flipper);
cxt = this;
viewPageAdapter = new MyPagerAdapter();
viewPager = (ViewPager) findViewById(R.id.mypager);
viewPager.setAdapter(viewPageAdapter);
viewFlipper = (ViewFlipper)findViewById(R.id.flipper);
slideLeftIn = AnimationUtils.loadAnimation(this, R.anim.slide_left_in);
slideLeftOut = AnimationUtils.loadAnimation(this, R.anim.slide_left_out);
slideRightIn = AnimationUtils.loadAnimation(this, R.anim.slide_right_in);
slideRightOut = AnimationUtils.loadAnimation(this, R.anim.slide_right_out);
gestureDetector = new GestureDetector(new VerticalGesture());
gestureListener = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (gestureDetector.onTouchEvent(event)) {
return true;
}
return false;
}
};
}
public boolean onTouchEvent(MotionEvent event) {
if (gestureDetector.onTouchEvent(event))
return true;
else
return false;
}
和 onFling 工具:
public class VerticalGesture extends GestureDetector.SimpleOnGestureListener{
private static final float SWIPE_MAX_OFF_PATH = 200;
private static final float MIN_DISTANCE_SWIPE = 10;
private static final float MIN_VELOCITY = 10;
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
try {
if (Math.abs(e1.getX() - e2.getX()) > SWIPE_MAX_OFF_PATH)
return false;
// top to down swipe
if(e1.getY() - e2.getY() > MIN_DISTANCE_SWIPE && Math.abs(velocityY) > MIN_VELOCITY) {
viewFlipper.setInAnimation(slideLeftIn);
viewFlipper.setOutAnimation(slideLeftOut);
viewFlipper.showNext();
} else if (e2.getY() - e1.getY() > MIN_DISTANCE_SWIPE && Math.abs(velocityY) > MIN_VELOCITY) {
viewFlipper.setInAnimation(slideRightIn);
viewFlipper.setOutAnimation(slideRightOut);
viewFlipper.showPrevious();
}
} catch (Exception e) {
// nothing
}
return false;
}
@Override
public boolean onDown(MotionEvent e) {
return true;
}
}
PagerAdapter 类:
public class MyPagerAdapter extends PagerAdapter{
@Override
public int getCount() {
return NUM_MAX_VIEWS;
}
@Override
public Object instantiateItem(View collection, int position) {
TextView tv = new TextView(cxt);
tv.setText("Dashboard " + position);
tv.setTextColor(Color.WHITE);
tv.setTextSize(30);
((ViewPager) collection).addView(tv,0);
return tv;
}
@Override
public void destroyItem(View collection, int position, Object view) {
((ViewPager) collection).removeView((TextView) view);
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view==((TextView)object);
}
@Override
public void finishUpdate(View arg0) {}
@Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {}
@Override
public Parcelable saveState() {
return null;
}
@Override
public void startUpdate(View arg0) {}
}
欢迎任何指南或资源。谢谢