我想通过了解触摸位置(x,y)坐标来获取Gridview的子视图。
case MotionEvent.ACTION_MOVE:
for(int i = 0; i < gridView.getChildCount(); i++)
{
//check if finger position is above any child
ImageView gridChild = (ImageView) gridView.getChildAt(i);
if(checkIntersection((int) event.getX(), (int) event.getY(), gridChild.getLeft(), gridChild.getRight(), gridChild.getTop(), gridChild.getBottom()))
{
gridChild.setImageResource(R.drawable.red_square);
break;
}
}
break;
我有上面的代码,但这种情况每秒发生多次,我相信它太强烈了。我想如果我能够通过使用触摸x,y坐标来获取用户正在触摸的子View对象,我不需要遍历所有孩子以找到他们正在触摸的那个。
checkIntersection()只是给出true或false,具体取决于手指位置是否位于Gridview子对象的矩形中。 Image showing how the checkIntersection function works.
更新: 这是整个代码块
//find the gridview view and assing it to a variable
final GridView gridView = (GridView) findViewById(R.id.gridView_boxes);
gridView.setAdapter(new ImageAdapter(this));
//when user lifts finger off the screen, reset all boxes
gridView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getActionMasked();
switch (action) {
//when finger is lifted off the gridView object
case MotionEvent.ACTION_UP:
//TODO after user lifts finger check if the path they chose has no obstacles
for (int i = 0; i < gridView.getChildCount(); i++)
{
ImageView gridChild = (ImageView) gridView.getChildAt(i);
gridChild.setImageResource(R.drawable.blue_square);
}
Log.d("SMEMS", "UP " + String.valueOf(action));
break;
//when finger touches the gridView
case MotionEvent.ACTION_DOWN:
//loop through all childs
for(int i = 0; i < gridView.getChildCount(); i++)
{
//check if finger position is above any child
ImageView gridChild = (ImageView) gridView.getChildAt(i);
if(checkIntersection((int) event.getX(), (int) event.getY(), gridChild.getLeft(), gridChild.getRight(), gridChild.getTop(), gridChild.getBottom())) {
gridChild.setImageResource(R.drawable.red_square);
break;
}
}
Log.d("SMEMS", "DOWN. Y value: " + String.valueOf(event.getY()) + ", X value: " + String.valueOf(event.getX()));
break;
case MotionEvent.ACTION_MOVE:
//TODO check if there is a more efficient way of doing this without a loop
//loop through all childs
for(int i = 0; i < gridView.getChildCount(); i++)
{
//check if finger position is above any child
ImageView gridChild = (ImageView) gridView.getChildAt(i);
if(checkIntersection((int) event.getX(), (int) event.getY(), gridChild.getLeft(), gridChild.getRight(), gridChild.getTop(), gridChild.getBottom())) {
gridChild.setImageResource(R.drawable.red_square);
break;
}
}
break;
}
return true;
}
});