0

我正好有 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 循环并设置它们的文本?

4

3 回答 3

9

如果你给你的TextView  as id R.id.textView1.. R.id.textView21,你可以使用 getIdentifierTextView从它的名字中检索 s 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); 
  }
}
于 2013-06-20T15:54:02.027 回答
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("...");
}
于 2013-06-20T16:00:22.667 回答
0

这个线程非常坚持,但我面临同样的需求:遍历我的布局结构并在每个 TextView 上做一些事情。在以多种方式对其进行谷歌搜索后,我最终决定编写自己的实现。你可以在这里找到它:

/*  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));
        }
    }
}
于 2017-11-27T19:11:20.360 回答