android setOnclickListener onClick方法非最终变量

时间:2012-08-01 10:28:51

标签: java android

我是Android编程新手 我想使用for循环来做类似的事情 这是我的代码:

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方法“i”中存在错误:
Cannot refer to a non-final variable i inside an inner class defined in a different method

3 个答案:

答案 0 :(得分:0)

尝试在final之前添加int i

答案 1 :(得分: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));
}

答案 2 :(得分:0)

  

for(int i = 0; i&lt; something.length; i ++){

 final int inmutable_index = i;

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

}

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