我需要实现一个列表视图,当向一侧滑动一行时,所有其他行将滑动到另一侧。 我的所有行都在屏幕上(.2-7行。)
我知道我可以在适配器中获取视图。 但是如何才能获得被触摸的视图(未点击)。
我不确定如何开始实施此功能。
有什么建议吗?
谢谢, 伊兰
答案 0 :(得分:1)
您可以使用View.setOnTouchListener(..)
。
以下是一些示例代码:
public class SwipeTouchListener implements View.OnTouchListener {
private ListView listView;
private View downView;
public SwipeTouchListener(ListView listView) {
this.listView = listView;
}
@Override
public boolean onTouch(View v, MotionEvent motionEvent) {
switch (motionEvent.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
// swipe started, get reference to touched item in listview
downView = findTouchedView(motionEvent);
break;
case MotionEvent.ACTION_MOVE:
if (downView != null) {
// view is being swiped
}
break;
case MotionEvent.ACTION_CANCEL:
if (downView != null) {
// swipe is cancelled
downView = null;
}
break;
case MotionEvent.ACTION_UP:
if (downView != null) {
// swipe has ended
downView = null;
}
break;
}
}
}
private View findTouchedView(MotionEvent motionEvent) {
Rect rect = new Rect();
int childCount = listView.getChildCount();
int[] listViewCoords = new int[2];
listView.getLocationOnScreen(listViewCoords);
int x = (int) motionEvent.getRawX() - listViewCoords[0];
int y = (int) motionEvent.getRawY() - listViewCoords[1];
View child = null;
for (int i = 0; i < childCount; i++) {
child = listView.getChildAt(i);
child.getHitRect(rect);
if (rect.contains(x, y)) {
break;
}
}
return child;
}
}
要使用它:
SwipeTouchListener swipeTouchListener = new SwipeTouchListener(listView);
listView.setOnTouchListener(swipeTouchListener);