我编写了一个活动,当用户只按下一个按钮时,背景会随机变化。我将背景图像放在可绘制文件中,并在值中创建了这些图像的数组。这是我现在得到的:
final LinearLayout background = (LinearLayout)findViewById(R.id.back);
Button button = (Button)findViewById(R.id.button1);
Resources res = getResources();
final TypedArray myImages = res.obtainTypedArray(R.array.image);
button.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
Random r = new Random(myImages.length());
int b = r.nextInt();
background.setBackgroundResource(b);
}
});
和数组:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<array name="image">
<item>@drawable/background</item>
<item>@drawable/background_blue</item>
<item>@drawable/background_pink</item>
<item>@drawable/background_orange</item>
</array>
</resources>
好像没什么问题,但是每次启动模拟器checkout总是显示activity停止了
谁能告诉我我的代码有什么问题?我会很感激的!!!
TO:Ashok logcat 显示这些错误
E/AndroidRuntime(802): FATAL EXCEPTION: main E/AndroidRuntime(802):java.lang.ArrayIndexOutOfBoundsException:length=456;index=1647793160
E/AndroidRuntime(802): at android.content.res.TypedArray.getResourceId(TypedArray.java:570)
E/AndroidRuntime(802): at com.example.cathy.MainActivity$1.onClick(MainActivity.java:39)
E/AndroidRuntime(802): at android.view.View.performClick(View.java:4240)
E/AndroidRuntime(802): at android.view.View$PerformClick.run(View.java:17721)
E/AndroidRuntime(802): at android.os.Handler.handleCallback(Handler.java:730)
E/AndroidRuntime(802): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(802): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(802): atandroid.app.ActivityThread.main(ActivityThread.java:5103)
E/AndroidRuntime(802): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(802): at java.lang.reflect.Method.invoke(Method.java:525)
E/AndroidRuntime(802): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
E/AndroidRuntime(802): atcom.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
E/AndroidRuntime(802): at dalvik.system.NativeStart.main(Native Method)