我想用 GridView 布局做一个活动。我将能够在gridview的元素上拖动手指来多选项目(例如Ruzzle)。当我举起手指时,我必须显示我选择了多少项目。
问问题
1217 次
1 回答
3
我知道这是一个老问题,但最近我们遇到了同样的问题,我们想出了一些办法。
假设您要将单元格的颜色更改为绿色。您只需要调用GridView.setOnTouchListener
并实现OnTouchListener
类似于以下内容:
...
private final int SELECTED_CELL_COLOR = Color.GREEN;
private int mPosition = GridView.INVALID_POSITION;
private boolean mSelecting = false;
...
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getActionMasked();
switch (action){
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
int x = (int)event.getX();
int y = (int)event.getY();
GridView grid = (GridView)v;
int position = grid.pointToPosition(x, y);
if(position != GridView.INVALID_POSITION) {
v.getParent().requestDisallowInterceptTouchEvent(true); //Prevent parent from stealing the event
View cellView = (View)grid.getItemAtPosition(position);
switch (action){
case MotionEvent.ACTION_DOWN:
mSelecting = true;
mPosition = position;
cellView.setBackgroundColor(SELECTED_CELL_COLOR);
break;
case MotionEvent.ACTION_MOVE:
if (mPosition != position) {
mPosition = position;
cellView.setBackgroundColor(SELECTED_CELL_COLOR);
} else {
//Repeated cell, noop
}
break;
case MotionEvent.ACTION_UP:
mSelecting = false;
mPosition = GridView.INVALID_POSITION;
//Here you could call a listener, show a dialog or similar
break;
}
}else{
if(mSelecting){
mSelecting = false;
}
}
break;
case MotionEvent.ACTION_CANCEL:
mSelecting = false;
break;
}
return true;
}
于 2013-09-28T22:52:12.557 回答