2012-08-24 34 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管理的視圖時,我遇到了同樣的問題。它可能會導致觸摸反應不佳。

相關問題