Android上动态添加的Text View上的内存泄漏 [英] Memory leaks on dynamically added Text View on Android

查看:63
本文介绍了Android上动态添加的Text View上的内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有LinearLayout,可以在其中动态添加和删除TextView.要删除它们,我只是打电话给 .removeAllViews();当然,这会导致巨大的内存泄漏.是他们释放内存的任何方式,还是我这边的建筑设计缺陷.

I have LinearLayout in which i dinamically add and remove TextView. To remove them i just call .removeAllViews(); This off course causes a huge memory leak. Is their any way i release the memory or it's just an architectural design flaw on my side.

      public void myUpdateFunction() {

            //...

    ((ViewGroup) findViewById(R.id.WordList)).removeAllViews();

    ArrayList<String> anagrams = model.getAnagrams();

    for (int i = 0; i < anagrams.size(); i++) {
        String word = anagrams.get(i);
        if (model.getFound(i)) {
            addWord(word);
        } else {
            addWord(word.length());
        }
    }

            //...
       }

public void addWord(String word) {
    ViewGroup list = (ViewGroup) findViewById(R.id.WordList);
    TextView v = new TextView(this);
    LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT);

    v.setLayoutParams(lparams);
    v.setTextColor(Color.BLACK);
    v.setText(word);
    list.addView(v);

}

推荐答案

内存泄漏在哪里?您不需要像在C/C ++中那样释放内存.如果没有更多引用,GC将收集您的TextView.

Where is the memory leak? You don't need to release memory as you had to do in C/C++. The GC will collect your TextViews if there are no more references to them.

这篇关于Android上动态添加的Text View上的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆