以编程方式删除布局

7

我有一个应用程序活动的以下 XML 结构。现在我想通过代码以可编程方式删除 ID 为 layer1Front 的子 RelativeLayout。我该如何做到这一点呢?我不想隐藏它,因为应用程序中存在内存问题,所以我需要将其删除。此外,在某种程度上删除后,我的应用程序比当前版本更轻和更快吗?

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/layer1Front" >
    </RelativeLayout>   
    <HorizontalScrollView android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <FrameLayout android:layout_width="wrap_content"
            android:layout_height="fill_parent"                   
            android:id="@+id/parallaxLayers"        
            android:visibility="gone">      
        </FrameLayout>
    </HorizontalScrollView>
    <RelativeLayout android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/frontView">

    </RelativeLayout>       

</RelativeLayout>

可能是重复的问题:如何从Android布局中删除子布局?(https://dev59.com/mFHTa4cB1Zd3GeqPRW6O) - SERPRO
1
我希望你已经尝试了View.GONE。 - ValayPatel
1
我不想隐藏布局。我想要删除它。 - Ayaz Alavi
为什么你不想用GONE来隐藏它? - Alexander Kulyakhtin
因为从内存中删除元素可能会使我的屏幕更快。 - Ayaz Alavi
1
正好相反:您不希望创建太过复杂的布局,因为它可能会使您的屏幕变慢。 - Alexander Kulyakhtin
2个回答

32

最简单的方法是:

findViewById(R.id.layer1front).setVisibility(View.GONE);

但是你也可以有这样的情况

View root = findViewById(R.id.your_root);
root.removeView(yourViewToRemove);

不,删除它后,您的应用程序不会变得更轻或更快。


2
尝试获取父布局,然后移除子项。
parentView.remove(child) 

我希望这个能够运行。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接