【发布时间】:2018-01-28 03:23:39
【问题描述】:
我想通过使用将 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]); }
**
【问题讨论】:
-
将 id 放入列表/数组并循环遍历它们?
-
是的。我同意@bub
标签: android for-loop optimization textview