2012-08-01 42 views
1

我是Android编程新手。
我想使用for循环来做类似的事情。
这里是我的代码:android setOnclickListener onClick方法非最终变量

int stubs[] = {R.id.stub_1, R.id.stub_2, R.id.stub_3}; 
View viewStubs[] = {stub_1, stub_2e, stub_3}; 
Button buttons[] = {button2, button3, button4}; 
button2 = (Button)findViewById(R.id.button2); 
button3 = (Button)findViewById(R.id.button3); 
button4 = (Button)findViewById(R.id.button4); 
for(int i=0; i<buttons.length; i++){ 
      buttons[i].setOnClickListener(new View.OnClickListener() {  
       public void onClick(View v) { 
        if(viewStubs[i] == null){ 
         viewStubs[i] = ((ViewStub)findViewById(stubs[i])).inflate(); 
        } 

       } 
      } 
     } 

然而,在方法的onClick “我” 的错误:
Cannot refer to a non-final variable i inside an inner class defined in a different method

+0

检查以下问题 http://stackoverflow.com/questions/1299837/cannot-refer-to-a-non-final-variable-inside-an-inner-class-defined-in-a -differen – barrel 2012-08-01 10:32:11

+0

在Java中没有关闭的版本少于7!你不能在内部类中使用局部var'i'。你应该重写你的代码 – Serjio 2012-08-01 10:36:49

+1

你可以做一个最终的int var并将它分配给我。然后将新的var传递给内部类... – Shark 2012-08-01 10:40:38

回答

0

尝试int i之前添加final

+0

这有帮助不会工作。在for循环中添加final变量意味着变量值不能被更改,因此它会开始抛出一些其他错误,如“最终局部变量不能被赋值”。 – 2012-08-01 10:33:30

+0

这是错误的。我们不能在for循环变量i中添加最终变量if – jjLin 2012-08-01 10:35:21

+0

想象循环遍历最终变量,并且得到为什么它是一个问题。 – Shark 2012-08-01 10:37:26

0

viewStubs数组应该是this类的属性(它似乎可能是静态的)。

int stubs[] = {R.id.stub_1, R.id.stub_2, R.id.stub_3}; 
// viewStubs should be a property of this class (maybe static) 
viewStubs[] = {stub_1, stub_2, stub_3}; 

Button buttons[] = { 
    (Button)findViewById(R.id.button2), 
    (Button)findViewById(R.id.button3), 
    (Button)findViewById(R.id.button4) 
}; 

for (int i=0; i<buttons.length; i++) { 
    View.OnClickListener listener = new View.OnClickListener() { 
     private int viewId; 

     private int stubId; 

     public void onClick(View v) { 
      if (viewStubs[stubId] == null) { 
       viewStubs[stubId] = (ViewStub)findViewById(viewId).inflate(); 
      } 
     } 

     public View.OnClickListener setIds(int vid, int sid) { 
      viewId = vid; 
      stubId = sid; 
      return this; 
     } 
    } 
    buttons[i].setOnClickListener(listener.setIds(stubs[i], i)); 
} 
0

对(INT I = 0;我< something.length;我++){

final int inmutable_index = i; 

btn.setOnClickListener(new OnClickListener(){...}); 

}

现在可以使用内部for循环最终变量inmutable_index没有任何问题,只需替换inmutable_index变量的内部类中i变量的所有用法。