android - 如何在 for 循环中实现一个 TextView 对象数组?

标签 android for-loop optimization textview

我想通过将 TextView 对象 a、b、c、d、e 用作数组元素的 for 循环来最小化代码。两者都用于 findViewById 和 setOnClickListener 实现。非常感谢任何针对此特定编码的可行演练!^__^

  • 以下是我通常如何实现 TextView。但是我 我厌倦了不必要地写这么多行。

    TextView a,b,c,d,e;

        a=(TextView)findViewById(R.id.A);
        b=(TextView)findViewById(R.id.B);
        c=(TextView)findViewById(R.id.C);
        d=(TextView)findViewById(R.id.D);
        e=(TextView)findViewById(R.id.E);
    
        a.setOnClickListener(this);
        b.setOnClickListener(this);
        c.setOnClickListener(this);
        d.setOnClickListener(this);
        e.setOnClickListener(this);
    
  • 我的问题是我是否可以使用循环来设置所有已经初始化的 TextView 对象可以毫无问题地调用 setOnClickListener() 如下所示:

    TextView a,b,c,d,e;
    
    a=(TextView)findViewById(R.id.A);
    b=(TextView)findViewById(R.id.B);
    c=(TextView)findViewById(R.id.C);
    d=(TextView)findViewById(R.id.D);
    e=(TextView)findViewById(R.id.E);
    

    TextView[] textViews = {a, b, c, d, e};

    for (int count = 0; count < textViews.length; count++) {
        textViews[count].setOnClickListener(this);
    }
    

**

  • 我只想知道如何初始化 TextView 对象 a,b,c,d,e同理,我给他们展示给setOnClickListener?像这样,

    TextView[] textViews = {a, b, c, d, e};
    
    int[] textViewIds = {R.id.a, R.id.b, R.id.c, R.id.d, R.id.e};
    
    for (int count = 0; count < textViews.length; count++) {
        textViews[count] = (TextView)findViewById(textViewIds[count]);
    }
    

**

最佳答案

这就是我要写的(我这里没有编译器,很抱歉有错误)

ArrayList<TextView> textViews = new ArrayList<TextView>();

int[] tvIds = {R.id.A,R.id.B,R.id.C,R.id.D,R.id.E};

for(int index= 0; index<tvIds.length/* or .count forgot sorry*/; index++){   

 TextView tv = (TextView)findViewById(tvIds[index]));
 tv.setOnClickListener(this);

 textViews.add(tv);

}

或者您可以使用@Hank Moody 的回答,butterknife 非常简单。

关于android - 如何在 for 循环中实现一个 TextView 对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46580398/

相关文章:

C++:优化列表

android - Recyclerview 滚动故障

android - 通知图标的背景

android - 由于错误 -12,无法分配 CursorWindow

启动新 Activity 后 Android 服务连接泄漏

java - 嵌套 java 循环的作用域问题

python - 在 Python 中循环子字典时出现意外输出

C++ for 循环逻辑 : break after getting strings from cmdline arguments?

php - PHP增加写页面速度

c++ - 有没有办法通过 LLVM 启用 avx2 指令集而无需自动矢量化