当用户滑动包含这些视图的布局时,我正在寻找一种更改TextViews
内容的方法。我的目标是这样的:
我正在尝试使用SimpleOnGestureListener
执行此操作(代码如下)。问题:当我从左向右滑动时,i的值变为-1,并且后续滑动不会发生反应。从右到左滑动会导致i变为1(地狱为零?)并且View会再次停止对滑动的反应。我做错了什么?
public class MainActivity extends Activity {
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
private GestureDetector gestureDetector;
public View mainview;
public TextView lol;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gestureDetector = new GestureDetector(new MyGestureDetector());
mainview = (View) findViewById(R.id.mainView);
lol = (TextView) findViewById(R.id.textView2);
mainview.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (gestureDetector.onTouchEvent(event)) {
return true;
}
return false;
}
});
}
class MyGestureDetector extends SimpleOnGestureListener {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
int i = 0;
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) {
i++;
lol.setText("Text" + " " + Integer.toString(i));
return true;
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
i--;
lol.setText("Text" + " " + Integer.toString(i));
return true;
}
return false;
}
@Override
public boolean onDown(MotionEvent e) {
return true;
}
}
}
答案 0 :(得分:2)
为什么不使用viewPager?它完全符合您的需求并支持指标。有一些带有指示器的自定义库,您可以在其中找到所需的确切指示器,例如: this one is nice
答案 1 :(得分:1)
使用图库或水平ScrollView或ViewPager
而不是管理手势