我想用GridView布局做一个活动。我将能够多次选择项目在gridview的元素上拖动我的手指(例如Ruzzle)。当我举起手指时,我必须显示我选择了多少项目。
答案 0 :(得分: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;
}