您好我正在尝试创建一个Android应用程序来显示图像,以便您可以点击下一个'按钮,然后下一个图像显示。到目前为止,我有这个方法
public void buttonClick(){
imgView = (ImageView)findViewById(R.id.imgView);
buttonS = (Button)findViewById(R.id.button);
buttonS.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
current_image_index++;
current_image_index = current_image_index % images.length;
imgView.setImageResource(images[current_image_index]);
}
}
);
}
然而,当我尝试运行它时,当我点击' next'时,我得到一个java.lang.OutOfMemoryError。按钮两次。难道我做错了什么?我的图像数组如下所示:
int[] images = {R.drawable.img};
我尝试更改Manifest文件以包含
android:largeHeap="true"
这是我设置变量并调用上面方法的地方
public class MainActivity extends AppCompatActivity {
private static ImageView imgView;
private static Button buttonS;
private int current_image_index;
int[] images = {R.drawable.dog,R.drawable.img};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonClick();
}
堆栈跟踪是:
08-29 23:17:34.781 15450-15450/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.daniel.firstapp, PID: 15450
java.lang.OutOfMemoryError: Failed to allocate a 2070252108 byte allocation with 16777216 free bytes and 482MB until OOM
at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:816)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:637)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:1019)
at android.content.res.Resources.loadDrawableForCookie(Resources.java:3778)
at android.content.res.Resources.loadDrawable(Resources.java:3651)
at android.content.res.Resources.getDrawable(Resources.java:1865)
at android.content.Context.getDrawable(Context.java:408)
at android.widget.ImageView.resolveUri(ImageView.java:752)
at android.widget.ImageView.setImageResource(ImageView.java:408)
at com.example.daniel.firstapp.MainActivity$1.onClick(MainActivity.java:40)
at android.view.View.performClick(View.java:5217)
at android.view.View$PerformClick.run(View.java:20983)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6141)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
答案 0 :(得分:2)
这是因为应用程序为所有映像处理内存的分配堆很小。您可以在Android清单文件中增加它。
指定
android:largeHeap="true"
作为<application>
代码
例如:
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:largeHeap="true"
android:theme="@style/AppTheme" >
并查看是否可以解决问题。