当我执行大循环时,应用程序占用过多 RAM

App spends too much RAM when I do large loops

我有这段代码,我想做同样的事情,但要花更少的内存。有什么想法可以在我生成的 300 个 ImageView 或类似的东西中设置一个图像加载器来解决这个问题吗?

DisplayMetrics lDisplayMetrics = getResources().getDisplayMetrics();
int widthPixels = lDisplayMetrics.widthPixels;
for (int getDrawables = 0; getDrawables < 300; getDrawables++)
{
    final ImageView icoView = new ImageView(ImageEditor.this);
    icoView.setImageResource(getResources().getIdentifier("icon_"+getDrawables, "drawable", getPackageName()));
    icoView.setLayoutParams(new LinearLayout.LayoutParams(widthPixels/7,widthPixels/7));
    gridlayout.addView(icoView);
    int idGen = View.generateViewId();
    icoView.setId(idGen);
    icoView.setTag("icon_"+getDrawables);
    gridlayout.setColumnCount(6);
}

不要在布局中添加太多 ImageView。无论如何,我认为它们不会同时全部可见。使用类似于 GridView or a RecyclerView 的东西来为您管理视图的回收。

解法: 添加 new drawables 但分辨率较低,并将其用于我的贴纸选择器。使用 GridView 作为 Recycler 我只减少了 500MB 的 RAM 使用。 我看到的另一种方法是将可绘制对象转换为位图,然后为位图设置调整大小。