我有 2 个自定义视图:1. BoardView 2. BallView。我将 BallView 添加到 BoardView 并将 BoardView 添加到我的布局中。
当我使用 ClickListener 和 TouchListener 单击 BallView 时,没有任何反应。好像 BoardView 与 BallView 区域重叠。
代码:
board = new BoardView(this);
ball = new BallModel(100, 200,50,screenWidth, screenHeight);
ballView = new BallView(this, ball);
ballView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event)
{
System.out.println("Hey");
return true;
}
});
ballView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
System.out.println("Hey");
}
});
board.addView(ballView);
更新:
public class BoardView extends View
{
private List<View> mShapes = new ArrayList<View>();
public BoardView(Context context)
{
super(context);
}
public void addView(View view)
{
mShapes.add(view);
}
@Override
public void onDraw(Canvas canvas)
{
super.onDraw(canvas);
for(int i=0; i<mShapes.size(); i++)
{
View view = mShapes.get(i);
view.draw(canvas);
}
}
}
public class BallView extends View
{
BallModel mBall;
Paint mBallPaint;
public BallView(Context context, BallModel ball)
{
super(context);
mBall = ball;
}
private Paint getPaint()
{
if(mBallPaint == null)
{
mBallPaint = new Paint();
mBallPaint.setColor(mBall.getColor());
}
return mBallPaint;
}
@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
Paint paint = getPaint();
paint.setColor(mBall.getColor());
canvas.drawCircle(mBall.getX(), mBall.getY(), mBall.getRadius(), paint);
}
}
有任何想法吗?