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

为什么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条)

报告相同问题?