我想通过使用for循环与TextView对象a,b,c,d,e作为数组的元素来最小化代码。用于findViewById和setOnClickListener实现。任何对此特定编码的可操作演练都非常感谢!^ __^如何在for循环中实现一个TextView对象数组?
以下是我通常如何执行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的一个 ,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 – MetaSnarf