0

this is my code..

for (int i = 0; i < 12; i++) 
   {
          buttons[i] = (Button)findViewById(R.id.buttonid);
        @Override
        public void onClick(View v) {
           // in this method I want to set the button text to the iteration variable 'i'
        }
    });
   }

my need is to get the iteration variable inside the onclick method. I tried by assigning the i value to another int variable(with and without using final) before the onclick method. But all this shows some errors.

Thanks in advance.

4

2 回答 2

2

通过在方法外部类的顶部声明 i 变量来使它成为全局变量。private int i; http://en.wikipedia.org/wiki/Global_variable

那你就不用int在for循环里面说了

for (i = 0; i < 12; i++) 
   {
         buttons[i] = (Button)findViewById(R.id.buttonid);
        @Override
        public void onClick(View v) {
           // in this method I want to set the button text to the iteration variable 'i'
        }
    });
   }

您也可以使用评论中提到的 final 修饰符,如果您希望我们调试您的错误,则必须发布您尝试使用它的方式。

于 2013-01-28T16:59:26.790 回答
0

您可以不再将i变量作为全局/最终变量,而是使用 的setTag()方法Button来传递值。

   for (int i = 0; i < 12; i++) {
          buttons[i] = (Button)findViewById(R.id.buttonid);
          buttons[i].setTag(new Integer(i));
          buttons[i].setOnClickListener(listener);
   }

并分离出OnClickListener

    OnClickListener listener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
               Integer iHolder = v.getTag();
               int i = iHolder.intValue();
               // set button text
        }
    };

这样,Button它本身就持有对值的引用,i而不是在全局范围内浮动或被声明final

于 2013-01-28T17:14:44.663 回答