我正好有20 TextView
,他们的id
是顺序的,即:
R.id.textView1, R.id.textView2, R.id.textView3 ...
我有一个for循环:
for (int i = 1; i < 21; i++) {
TextView textView = (TextView) findViewById(R.id.textView ...);//
textView.setText("...");
有没有办法让TextView
使用这个for循环并设置文本?
答案 0 :(得分:8)
如果您将TextView
作为身份R.id.textView1.. R.id.textView21
,则可以使用getIdentifier从其名称中检索TextView
的ID
for (int i = 1; i < 21; i++) {
String name = "textView"+i
int id = getResources().getIdentifier(name, "id", getPackageName());
if (id != 0) {
TextView textView = (TextView) findViewById(id);
}
}
答案 1 :(得分:1)
更有效的方法是创建一个整数数组并迭代它:
int[] textViewIDs = new int[] {R.id.textView1, R.id.textView2, R.id.textView3, ... };
for(int i=0; i < textViewIDs.length; i++) {
TextView tv = (TextView ) findViewById(textViewIDs[i]);
tv.setText("...");
}
答案 2 :(得分:0)
这个线程非常坚固,但我遇到了同样的需求:遍历我的布局结构并在每个TextView上做一些事情。在以多种方式对其进行了googlized后,我终于决定编写自己的实现。你可以在这里找到它:
/* Iterates through the given Layout, looking for TextView
---------------------------------
Author : Philippe Bartolini (PhB-fr @ GitHub)
Yes another iterator ;) I think it is very adaptable
*/
public void MyIterator(View thisView){
ViewGroup thisViewGroup = null;
boolean isTextView = false;
int childrenCount = 0;
try {
thisViewGroup = (ViewGroup) thisView;
childrenCount = thisViewGroup.getChildCount();
}
catch (Exception e){
}
if(childrenCount == 0){
try {
isTextView = ((TextView) thisView).getText() != null; // You can adapt it to your own neeeds.
}
catch (Exception e){
}
if(isTextView){
// do something
}
}
else {
for(int i = 0; i < childrenCount; i++){
MyIterator(thisViewGroup.getChildAt(i));
}
}
}