不确定标题是否描述得很好,我想要的是:
我的布局中有 9 个 TextView,分别命名为 tv1、tv2、...、tv9。
当然我可以访问它们中的每一个
TextView tv11 = (TextView) findViewById(R.id.tv1)
很多打字,所以我宁愿有一个循环和循环遍历这些项目,但是如何将 findViewbyId 包含到我可以相应地更改值的循环中?
Is there any reason why you can't iterate over the children of the containing ViewGroup? So you get the number of children with getChildCount
and then you can access each individual child with getChildAt
.
You may have to test whether a particularly child is an instance of TextView
if you have other views in the layout, but the basic concept is fairly straightforward.
您可以制作一个要循环遍历的 ID 数组。
IE:
public static final int TEXTVIEW_IDS = { R.id.tv1, R.id.tv2, R.id.tv3, etc.. };
在您的视图代码中:
for (int id : TEXTVIEW_IDS) {
((Textview) findViewById(id)).CallYourMethod();
}
如果你不能按照@James Holderness 的建议去做,这可能是一个合适的选择。