我创建了一个名为 ButtonList 的按钮数组,如下所示。
LinearLayout player=(LinearLayout)findViewById(R.id.playerlayout);
PlayerFirst=(Button)player.getChildAt(0);
for(int i=0;i<player.getChildCount();i++)
{
ButtonList.add((Button)player.getChildAt(i));
}
我需要依次增加这些按钮的值。(每次更改之间都有延迟)我有以下代码:
for( k=0;k<ButtonList.size();k++)
{
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
ButtonList.get(getK()).setText(getK()+1+"");
}
}, 1000);
}
这里 getK() 是 k 的访问器,以便在匿名函数中访问 k。
public int k;
public int getK()
{
return k;
}
我的应用程序崩溃。我究竟做错了什么?
LogCat 错误:
01-03 05:21:04.396: I/Process(1469): Sending signal. PID: 1469 SIG: 9
01-03 05:21:06.276: E/Trace(1535): error opening trace file: No such file or directory (2)
01-03 05:21:08.826: W/dalvikvm(1535): threadid=1: thread exiting with uncaught exception (group=0x2bd39930)
01-03 05:21:08.846: E/AndroidRuntime(1535): FATAL EXCEPTION: main
01-03 05:21:08.846: E/AndroidRuntime(1535): java.lang.IndexOutOfBoundsException: Invalid index 12, size is 12
01-03 05:21:08.846: E/AndroidRuntime(1535): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
01-03 05:21:08.846: E/AndroidRuntime(1535): at java.util.ArrayList.get(ArrayList.java:304)
01-03 05:21:08.846: E/AndroidRuntime(1535): at com.example.awari.MainActivity$1.run(MainActivity.java:129)
01-03 05:21:08.846: E/AndroidRuntime(1535): at android.os.Handler.handleCallback(Handler.java:725)
01-03 05:21:08.846: E/AndroidRuntime(1535): at android.os.Handler.dispatchMessage(Handler.java:92)
01-03 05:21:08.846: E/AndroidRuntime(1535): at android.os.Looper.loop(Looper.java:137)
01-03 05:21:08.846: E/AndroidRuntime(1535): at android.app.ActivityThread.main(ActivityThread.java:5039)
01-03 05:21:08.846: E/AndroidRuntime(1535): at java.lang.reflect.Method.invokeNative(Native Method)
01-03 05:21:08.846: E/AndroidRuntime(1535): at java.lang.reflect.Method.invoke(Method.java:511)
01-03 05:21:08.846: E/AndroidRuntime(1535): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-03 05:21:08.846: E/AndroidRuntime(1535): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-03 05:21:08.846: E/AndroidRuntime(1535): at dalvik.system.NativeStart.main(Native Method)