更新自定义 View 中的 TextView
我的活动中有一个半屏自定义视图和一个 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!");
I have a half screen custom view and a TextView in my activity.
<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" />
Upon clicking on the custom view, how can I update the TextView in my activity?
Currently I have this piece of coding in my custom view's onTouchEvent()
but it hits a NullPointerException in the setText()
part. Should I never update the TextView in my custom view?
TextView tvScore = (TextView) findViewById(R.id.tvScore);
tvScore.setText("Updated!");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您无法在自定义视图的代码中“查看”TextView tvScore。
findViewById()
从调用它的视图开始在层次结构中查找视图,如果您调用Activity.findViewById()
,则从层次结构根开始查找视图(当然这只有在setContentView()
之后才有效)。如果您的自定义视图是复合视图,例如包含一些 TextView 的线性图层,那么在其中使用
findViewById()
是有意义的。解决方案是在
onCreate()
中找到文本视图,然后以某种方式将其传递给自定义视图(例如某些set..()
方法)。编辑
如果在您的自定义视图中您有类似的内容:
您可以执行类似的操作:
这样您就可以在自定义视图的代码中引用textview。这就像某种设置。
You can't "see" the TextView tvScore in your custom view's code.
findViewById()
looks for views in the hierarchy starting from the view from which you're calling it, or from hierarchy root if you're callingActivity.findViewById()
(and of course this works only aftersetContentView()
).If your custom view was a compound view like say a linear layour containing some TextViews, then it would make sense using
findViewById()
in there.The solution is finding the textview for example in
onCreate()
and then passing it to the custom view in some way (like someset..()
method).EDIT
If in your custom view you have something like:
you can do something like:
so that since then you would have a reference to the textview inside your custom view's code. It would be like some sort of setup.