在自定义视图中更新TextView
-
15-11-2019 - |
题
我在我的活动中有一个半屏幕自定义视图和一个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()
一部分。我应该永远不会更新我的自定义视图中的TextView吗?
TextView tvScore = (TextView) findViewById(R.id.tvScore);
tvScore.setText("Updated!");
解决方案
您无法在自定义视图的代码中"看到"TextView tvScore。 findViewById()
在层次结构中查找从您调用它的视图开始的视图,或者从层次结构根(如果您调用)开始的视图 Activity.findViewById()
(当然,这只适用于之后 setContentView()
).
如果您的自定义视图是一个复合视图,比如说包含一些TextViews的线性layour,那么使用它是有意义的 findViewById()
在那里。
解决方案是找到textview,例如 onCreate()
然后以某种方式将其传递给自定义视图(如一些 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。这就像是某种设置。
不隶属于 StackOverflow