我是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
檢查以下問題 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
在Java中沒有關閉的版本少於7!你不能在內部類中使用局部var'i'。你應該重寫你的代碼 – Serjio 2012-08-01 10:36:49
你可以做一個最終的int var並將它分配給我。然後將新的var傳遞給內部類... – Shark 2012-08-01 10:40:38