我想通过将 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/