2012-08-24 38 views
0

我有延伸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); 
    } 
} 

孩子的(广场)是其中有一个自定义自定义视图的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,Samsung Galaxy Ace,Samsung galaxy mini上测试)。

+0

如果你还没有完成它,你可能应该在调用被覆盖的版本时调用'super.onLayout()',在其他任何事情完成之前。 – Closeratio

+0

我做不到。 onLayout()是ViewGroup的抽象方法。超级类没有实现。 – Jesus

回答

0

在您的MotionEvent.ACTION_DOWN中返回错误会导致某些GestureDetector(如果这是您正在使用的)方法不能被调用。尝试在那里返回true,看看它是否更好地响应。

本Android开发者页面可以帮助你:Making a View Interactive

0

有时坏的触摸响应可以通过适配器视图通过适配器打破管理的意见循环引起的。当我保存
引用由AdapterView管理的视图时,我遇到了同样的问题。它可能会导致触摸反应不佳。

相关问题