【问题标题】:Custom View not respond very well on touch events自定义视图对触摸事件的响应不是很好
【发布时间】: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


【解决方案1】:

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

此 Android 开发者页面可能会对您有所帮助:Making a View Interactive

【讨论】:

    【解决方案2】:

    有时,不好的触摸响应可能是由于 AdapterView 中的 Adapter 管理视图的循环中断造成的。我保存时遇到了同样的问题
    引用由 AdapterView 管理的视图。它可能会导致对触摸的不良反应。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多