removeAllViewsInLayout

时间:2018-09-19 20:43:48

标签: android android-fragments memory-leaks

我正在开发一个使用FragmentPagerAdapter来管理Fragments的应用程序。 在其中一个片段中,我可以执行以下操作:

  • 使用动态创建的组件(LinearLayout,ImageView,Button)填充片段的视图

  • 删除创建的视图

但是,当我尝试删除视图时,可能会发现一些严重的内存泄漏。 当我大量(测试产品)调用 populateItems() clearFragment() <时,Android Studio中的Android Profiler显示大部分内存没有从“图形”部分恢复。 / p>

这是我如何在Fragment中动态创建视图组件的方法:

@Override 
public void onViewCreated(View view, @Nullable Bundle savedInstanceState)
{
    ...
    // populate the layouts
    populateItems(view);
    ...
}

// THIS IS THE FUNCTION USED TO POPULATE THE FRAGMENT
public void populateItems(View vw)
{
    LinearLayout horizontalView;
    ImageView faceImg;
    Button renameBtn;

    fragment_id = (LinearLayout)getActivity().findViewById(R.id.fragment_cunoscuti);

    if(fragment_id != null)
    {
        for (int i = 0; i < files.length; i++)
        {
            String imagePath = Constants.getKnownPath() + File.separator + files[i].getName();

            // set the image view
            faceImg = new ImageView(getActivity());
            faceImg.setImageBitmap(FileUtils.getBitmapFromFile(imagePath));
            ....

            // create the button ...
            renameBtn = new Button(getActivity());

            ....
            // create this for some irrelevant reason :)
            horizontalView = new LinearLayout(getActivity());
            ....
            horizontalView.addView(faceImg);
            horizontalView.addView(renameBtn);

            ....
            fragment_id.addView(horizontalView,params);
        }
}

// THIS IS THE FUNCTION USED AT SOME POINT TO CLEAR THE FRAGMENT
public void clearFragment()
{
    if(fragment_id != null)
    {
        for(int x=0;x<fragment_id.getChildCount();x++)
        {
            if(fragment_id.getChildAt(x) instanceof LinearLayout)
            {
                LinearLayout FL = (LinearLayout) fragment_id.getChildAt(x);
                FL.removeAllViewsInLayout();
            }
        }
        fragment_id.removeAllViewsInLayout();
    }

    // added just for tests
    System.gc();
}

Q:我向stackoverflow查询类似的问题,但无法解决。 在尝试保持清理片段视图的功能时,如何避免内存泄漏?

谢谢。

0 个答案:

没有答案
相关问题