使用字符串代替 ID 的引用控件
引用 android 控件的典型方法是这样的:
TextView tv = (TextView)findViewById(R.id.tv);
其中 R.id.tv 是引用我的 xml 控件的整数。
问题是我想使用字符串“R.id.tv”进行参考。这可能吗?
假设我有多个控件:
tv1,
tv2,
tv3,
tv4,
tv5,
我如何将其放入某种循环中并通过控件进行交互。我想我会使用循环计数器来引用不同的控件。那要怎么做呢?谢谢。
Typical way to reference android control is something like this:
TextView tv = (TextView)findViewById(R.id.tv);
Where R.id.tv is integer referencing my xml control.
The thing is I would like to make reference using string "R.id.tv". Is that possible?
Let's say I have multiple controls:
tv1,
tv2,
tv3,
tv4,
tv5,
How would I put this into some sort of loop and interate through controls. I am thinking I would use loop counter to reference different controls. How's that to be done? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一种方法是将 ids 放入数组中并通过下标引用。
One approach is to put the ids into an array and reference by subscript.
接下来尝试
...
Try next
...
看看这个问题:
Have a look at this question:
我不明白你为什么要这样做,它非常丑陋,效率低下,并且可能会导致维护问题和错误。
为什么不使用集合(例如ArrayList)来存储对所有控件的引用?
I don't understand why you'd want to do this, it's pretty ugly, inefficient, and likely to cause maintenance issues and bugs.
Why not use a collection (e.g. ArrayList) to store references to all the controls?