在自定义视图中更新TextView

时间:2011-02-19 10:35:16

标签: android textview android-custom-view

我的活动中有半屏自定义视图和TextView。

<com.sted.test.mainView
    android:id="@+id/mainView" android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

<TextView android:id="@+id/tvScore" android:layout_height="wrap_content" android:layout_width="wrap_content"
    android:layout_alignParentLeft="true" android:layout_alignParentBottom="true" />

点击自定义视图后,如何更新活动中的TextView?

目前我在自定义视图onTouchEvent()中有这段编码,但它在setText()部分遇到NullPointerException。我是不是应该在自定义视图中更新TextView?

TextView tvScore = (TextView) findViewById(R.id.tvScore);
tvScore.setText("Updated!");

1 个答案:

答案 0 :(得分:4)

您无法在自定义视图的代码中“看到”TextView tvScore。 findViewById()从您调用它的视图开始查找层次结构中的视图,或者如果您正在调用Activity.findViewById(),则从层次结构根查找视图(当然这仅在setContentView()之后有效)。

如果你的自定义视图是一个复合视图,比如说包含一些TextView的线性图像,那么使用findViewById()就可以了。

解决方案是在onCreate()中查找textview,然后以某种方式将其传递给自定义视图(例如某些set..()方法)。

修改

如果在您的自定义视图中,您有以下内容:

public class CustomView extends View {
    ...
    TextView tvToUpdate;
    public void setTvToUpdate(TextView tv) {
        tvToUpdate = tv;
    }
    ...
}

你可以这样做:

protected void onCreate(Bundle bundle) {
    ...
    CustomView cv = (CustomView) findViewById(R.id.customview);
    TextView tv = (TextView) findViewById(R.id.tv);
    cv.setTvToUpdate(tv);
    ...
}

因此,从那时起,您将在自定义视图的代码中引用textview。这就像某种设置。