我正在尝试创建一个填充矩形的字段,如果移动手指,其下方的矩形会改变颜色。我尝试了很多方法,但我没有成功,我没有任何其他想法。现在我的代码看起来像这样,问题在于,只有当我的手指位于屏幕的左上角并且它为所有矩形着色时,着色(在ontouch中)才会激活。
public class MainActivity extends Activity implements OnTouchListener {
ImageView[][] buttons;
Button b;
TableLayout ButtonContainer;
RelativeLayout linar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
buttons=new ImageView[5][5];
linar=new RelativeLayout(this);
linar.setOnTouchListener(this);
setPos(0,0,100);
setContentView(linar);
}
void setPos(float startX, float startY, int size)
{
float actposX,actposY;
actposX=startX;
actposY=startY;
for (int i=0;i<5;i++){
for (int j=0;j<5;j++){
buttons[i][j]=new ImageView(this);
buttons[i][j].setLayoutParams(new RelativeLayout.LayoutParams(size, size));
buttons[i][j].setX(actposX);
buttons[i][j].setY(actposY);
if (j % 2 ==0){
buttons[i][j].setBackgroundColor(Color.YELLOW);
}
else
{ buttons[i][j].setBackgroundColor(Color.BLUE); }
actposX+=size;
linar.addView(buttons[i][j]);
}
actposY+=size;
actposX=startX;
}
}
@Override
public boolean onTouch(View v, MotionEvent event) {
for(int i =0; i< 5; i++)
{
for (int j=0; j< 5; j++)
{
Rect outRect = new Rect(buttons[i][j].getLeft(), buttons[i][j].getTop(), buttons[i][j].getRight(), buttons[i][j].getBottom());
if(outRect.contains((int)event.getX(), (int)event.getY()))
{
buttons[i][j].setBackgroundColor(Color.RED);
}
}
}
return true;
}
}
答案 0 :(得分:0)
你可以这样做,
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
final int action = event.getAction();
switch (action & MotionEventCompat.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
event.getX();
event.getY();
Log.d(TAG, "onTouchEvent DOWN: x " + selX + ", y " + selY);
break;
case MotionEvent.ACTION_MOVE:
event.getX();
event.getY();
Log.d(TAG, "onTouchEvent Move: x " + selX + ", y " + selY);
break;
case MotionEvent.ACTION_UP:
event.getX();
event.getY();
Log.d(TAG, "onTouchEvent UP: x " + selX + ", y " + selY);
break;
}
return true;
}
MotionEvent.ACTION_MOVE 将检测指针移动。你可以得到指针并做你的颜色填充部分。还要检查logcat以便更好地理解..祝你好运!
答案 1 :(得分:0)
我想通了...... getLeft(),getTop()..给出了0值,所以我改变了它:
outRect.top=(int) (buttons[i][j].getY());
outRect.bottom=(int) (buttons[i][j].getY()+buttons[i][j].getLayoutParams().height);
outRect.left=(int) (buttons[i][j].getX());
outRect.right=(int) (buttons[i][j].getX()+buttons[i][j].getLayoutParams().height);