【发布时间】:2012-08-24 15:32:38
【问题描述】:
我有一个扩展 ViewGroup 的自定义网格,我还有下一个 onLayout 和 measureChildrenSizes 方法:
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// .. tileSide calcultion ..
measureChildrenSizes(tileSide);
for (int i = 0; i < getChildCount(); i++) {
Square child = (Square) getChildAt(i);
int x = child.getColumn();
int y = child.getRow();
child.layout(x * tileSide, y * tileSide,
(x + 1) * tileSide, (y + 1) * tileSide);
}
}
private void measureChildrenSizes(int tileSide) {
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
measureChild(child, tileSide, tileSide);
}
}
childs (Square) 是自定义 View,具有自定义 onDraw 方法和 onTouch 回调方法:
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
rect.set(0, 0, getWidth(), getHeight());
gradient.setBounds(rect);
gradient.draw(canvas);
rectangle.setStrokeWidth(0.2f);
rectangle.setStyle(Style.STROKE);
rectangle.setColor(getResources().getColor(
R.color.puzzle_foreground));
canvas.drawRect(rect, rectangle);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
requestFocus();
changeState();
return false;
}
return super.onTouchEvent(event);
}
这会绘制一个正方形网格,其边长为 tileSide。除最后一列外,所有正方形都可以正常工作。有时他们不回应。
也许我在寻找错误的方向。
编辑:在模拟器中工作正常。它在真实设备上失败(在 Sony xperia u、三星 Galaxy Ace、三星 Galaxy mini 上测试)。
【问题讨论】:
-
如果您还没有这样做,您可能应该在调用覆盖的版本时调用
super.onLayout(),然后再进行任何其他操作。 -
我做不到。 onLayout() 是 ViewGroup 的抽象方法。超类没有实现。
标签: android view touch-event ondraw viewgroup