我刚开始使用 Android。我试过一个方向改变的应用程序。
我面临位图大小超出 VM 预算的问题。在 stackoverflow 中浏览了很多帖子,但无法找出问题所在。异常在 setContentView(R.layout.level1) 处抛出;在创建。当我改变方向时会发生这种情况。
我已经尝试了所有论坛和 stackoverflow,但无法弄明白。过去 3 天试图解决此问题。
使用 intent 和 startActivity 从按钮单击时的另一个 Activity 调用下面的类。
@Override
public void onCreate(Bundle savedInstanceState) {
Log.d("onCreate", "onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.level1);
if(!isOrientationChanged) //this part is executed if orientation is not changed (activity starts as usual)
{
drawableList = new ArrayList<Drawable>();
drawableList.add( getResources().getDrawable(colorEnum[0]));
drawableList.add( getResources().getDrawable(colorEnum[1]));
}
isOrientationChanged = false;
timeView = (TextView) findViewById(R.id.timeView);
colorButton = (Button) findViewById(R.id.game_button);
}
@Override
protected void onResume() {
scoreView = (TextView) findViewById(R.id.scoreView);
scoreView.setText("Score: " + score);
hand.postDelayed(runThread, 0);
super.onResume();
}
@Override
public Object onRetainNonConfigurationInstance() {
isOrientationChanged = true;
return null; //as you are not returning an object you are not leaking memory here
}
@Override
protected void onPause() {
hand.removeCallbacks(runThread);
super.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindDrawables(findViewById(R.id.RootView));
System.gc();
}
private void unbindDrawables(View view) {
if (view.getBackground() != null) {
view.getBackground().setCallback(null);
}
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
Log.d("onDestroy","Inside loop to getting child "+((ViewGroup) view).getChildAt(i));
unbindDrawables(((ViewGroup) view).getChildAt(i));
}
((ViewGroup) view).removeAllViews();
}
hand.removeCallbacks( runThread);
}
/** The run thread. */
Thread runThread = new Thread() {
@Override
public void run() {
timeView.setText("Time Left: " + timeLeftVal);
:
:
:
} else {
changeColor();
:
:
hand.postDelayed(runThread, GET_DATA_INTERVAL);
}
}
};
/**
* Change color.
*/
private void changeColor() {
colorButton.setBackgroundDrawable(drawableList.get(randomNum));
- 在 onCreate 方法中,创建一个可绘制列表并在第一次加载时对其进行初始化。
- 使用Thread随机设置按钮图片背景
- 调用 unbindDrawables() 方法 onDestroy 以便在方向改变时旧 View 将从内存中删除。
- hand.removeCallbacks(runThread) 也在 onPause 方法中被调用
- 在 onRetainNonConfigurationInstance() 中返回 null
我已经解决了这个问题。 小错误导致了这个大问题。我在 Handler 中使用了 Thread 而不是 Runnable。因此,removeCallback 没有按预期工作。
最佳答案
关于java - android - OutofMemoryError - 位图大小超出 VM 预算 - 方向改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8448531/