我想做一个GridView布局的活动。我将能够在网格视图的元素上拖动手指来选择多个项目(比如Ruzzle )。当我举起手指时,我必须表明我已经被选中了多少个项目。
发布于 2013-09-29 06:52:13
我知道这是一个古老的问题,但最近我们遇到了同样的问题,我们想出了一些东西。
假设您想要将单元格的颜色更改为绿色。您只需要调用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;
}
https://stackoverflow.com/questions/16032727
复制相似问题