1

我的布局中有一个自定义视图,布局中还有一个 TextView,如下所示:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:layout_alignParentTop="true" android:layout_centerInParent="true"
    android:text="Tiny" android:orientation="vertical">

<my.package.drawView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/my_view"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    />


<TextView android:text="Application Name" android:id="@+id/appName"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:textSize="30px" android:textStyle="italic" />
</LinerLayout>

我在活动的 onCreate 方法和自定义视图的 onDraw 方法中设置了对 TextView 的引用,我将 TextView 的文本更改如下:

public void onDraw(Canvas canvas) {
    tv.setText("player score: "+score);
}

但是在 ondraw 方法中设置文本会导致它进入无限循环。有人可以告诉我如何在调用自定义视图的 onDraw 方法中或之后更新 TextView 的文本。

4

4 回答 4

1

当您更改当前视图中的视觉事物时,即在这种情况下为 textview。整个可见区域都被重绘,并且作为 my.package.drawView 的一部分被告知要绘制自身,因此是无限循环。

应避免更改 onDraw 中的视觉属性,并且设计不正确。

也许您需要某种计时器来更新分数或在游戏中发生某些事情时增加分数的其他地方?

于 2011-12-23T06:01:10.170 回答
1

首先你为什么要这么做?一旦您更改文本,就会在 TextView 的情况下调用 On Draw。

调用 setText 将在内部调用 invalidate ,最终将导致再次调用 onDraw 。

如果您只想处理文本更改,请实施 aTextChangeListner并完全满足需要。

不要把这些东西放在 onDraw ... onDraw 功能应该用来玩画布。

如果您真的想在 onDraw 中工作,请使用

canvas.drawText(String text, float x, float y, Paint paint)

更多参考:http: //developer.android.com/reference/android/graphics/Canvas.html

于 2011-12-23T06:03:05.493 回答
0

当你说它进入无限循环时,你到底是什么意思?我建议您确保您的自定义视图确实按照您的预期重新绘制。一种简单的方法是在 textView 中记录您正在更新的任何内容:

Log.d("my.package.drawView", "player score: "+score);

该日志多久打印一次?

于 2011-12-23T06:00:06.970 回答
0

You get an infinite loop because setText calls onDraw, and onDraw calls setText. You can avoid this if you call setText only if the text has changed:

void setTextIfChanged(TextView tv, CharSequence text) {
    if (!text.equals(tv.getText()))
        tv.setText(text);
}

public void onDraw(Canvas canvas) {
    setTextIfChanged(tv, "player score: " + score);
}
于 2014-09-14T23:40:56.623 回答