画布没有重新绘制

时间:2013-09-17 18:10:16

标签: android android-canvas android-tabs

选择标签时尝试在画布上重绘:

@Override
public void onTabChanged(String tabId) {
   for(int i=0;i<mTabHost.getTabWidget().getChildCount();i++)
        {
         mTabHost.getTabWidget().getChildAt(i).setSelected(false); //unselected
        }
         mTabHost.getTabWidget().getChildAt(mTabHost.getCurrentTab()).setSelected(true); // selected
}

然后在自定义视图中执行:

public class TabIndicator extends LinearLayout {
...
public void setSelectedTab(boolean isSelected){
    this.isSelected = isSelected;

    if(isSelected){
        this.invalidate();
        this.postInvalidate();
    }
}
 @Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    if(isSelectedTab()){
        Paint paint2 = new Paint();
        Path path2 = new Path();
        paint2.setStyle(Paint.Style.STROKE);
        paint2.setStrokeWidth(10);
        paint2.setColor(Color.parseColor(getResources().getString(R.string.NAVY_BLUE)));
        path2.moveTo(width*(1/4f), height);
        path2.lineTo(width*(3/4f), height);
        path2.close();
        canvas.drawPath(path2, paint2);
    }
}

即使重复调用draw也没有任何反应。 (通过log.d检查) 它仅在创建布局时第一次绘制。

1 个答案:

答案 0 :(得分:2)

您正在扩展ViewGroup

http://developer.android.com/reference/android/view/ViewGroup.html

默认情况下,不会为ViewGroup对象调用onDraw()。相反,您可以覆盖dispatchDraw()

或者,您可以通过在构造函数中调用ViewGroup来启用setWillNotDrawEnabled(false)绘图。

https://groups.google.com/forum/?fromgroups#!topic/android-developers/oLccWfszuUo

检查Romain Guy的评论

我可以找到之前回答的类似问题的链接。有一个例子,请检查下面的链接

onDraw method not called in my application