llller 2011-09-02 00:59
浏览 360
已采纳

为什么TextView.onDraw会被调用???

[code="xml"]
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
android:id="@+id/title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="----"
/>
android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
android:id="@+id/btn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="change"
/>


[/code]
[code="java"]
public class MyTextViewDemo extends Activity {
private MyTextView mt;
private Button btn;
private TextView tv;
private int i = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mt = (MyTextView) findViewById(R.id.text);
tv = (TextView) findViewById(R.id.title);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
tv.setText("adsf:" + i++);
}
});
}
}
[/code]
自定义TextView
[code="java"]
public class MyTextView extends TextView {

public MyTextView(Context context) {
    super(context);
}

public MyTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public MyTextView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

@Override
protected void onDraw(Canvas canvas) {
    System.out.println("--------------- onDraw --------------");
    super.onDraw(canvas);
}

}
[/code]
现在的问题是,当点击button时,会改变title的值,但是MyTextView.onDraw也会被调用,而且点击几次就调用几次,这是为什么??

  • 写回答

9条回答 默认 最新

  • laopeng301 2011-09-02 23:13
    关注

    [code="java"]

    Drawing
    Drawing is handled by walking the tree and rendering each view that intersects the the invalid region.[color=red] Because the tree is traversed in-order, this means that parents will draw before (i.e., behind) their children, with siblings drawn in the order they appear in the tree.[/color] If you set a background drawable for a View, then the View will draw it for you before calling back to its onDraw() method.

    Note that the framework will not draw views that are not in the invalid region.

    To force a view to draw, call invalidate().

    [/code]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(8条)

报告相同问题?

悬赏问题

  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突