[英]Using OnTouchListener to implement a slider structure in android
我正在研究一个具有双滑块结构的项目。我正在使用ontouchlistener引起滑动。有两个滑块,一个是左滑块,另一个是右滑块。右滑块的滑动手势突然停止工作。我还没有对主类进行任何更改。当右滑块打开时,将调用一个Web服务在其中填充一个列表视图。
public class Swipe_Activity extends Activity {
LinearLayout swipe_layout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipe_layout=(LinearLayout) findViewById(R.id.layout_swipe);
swipe_layout.setOnTouchListener( new OnSwipeTouchListener(this));
}
public class OnSwipeTouchListener implements OnTouchListener {
private final GestureDetector gestureDetector;
public OnSwipeTouchListener (Context ctx){
gestureDetector = new GestureDetector(ctx, new GestureListener());
}
private final class GestureListener extends SimpleOnGestureListener {
private static final int SWIPE_THRESHOLD = 60;
private static final int SWIPE_VELOCITY_THRESHOLD = 60;
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
boolean result = false;
try {
float diffY = e2.getY() - e1.getY();
float diffX = e2.getX() - e1.getX();
if (Math.abs(diffX) > Math.abs(diffY)) {
if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (diffX > 0) {
onSwipeRight();
} else {
onSwipeLeft();
}
}
result = true;
}
/* else if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
if (diffY > 0) {
onSwipeBottom();
} else {
onSwipeTop();
}
}*/
// result = true;
} catch (Exception exception) {
exception.printStackTrace();
}
return result;
}
}
public void onSwipeRight() {
Log.i("Post", "right");
}
public void onSwipeLeft() {
Log.i("Post", "left");
Intent intent=new Intent(Swipe_Activity.this,Questions_Answers_Activity.class);
startActivity(intent);
}
public void onSwipeTop() {
Log.i("Post", "Top");
}
public void onSwipeBottom() {
Log.i("Post", "Bottom");
}
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return gestureDetector.onTouchEvent(event);
}
}
更改您的代码,例如
在GestureListener中
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
boolean result = false;
try {
float diffY = e2.getY() - e1.getY();
float diffX = e2.getX() - e1.getX();
if (Math.abs(diffX) > Math.abs(diffY)) {
if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (diffX > 0) {
onSwipeRight();
} else {
onSwipeLeft();
}
}
}
} catch (Exception exception) {
exception.printStackTrace();
}
return result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.