Android:如何以编程方式删除XML文件的所有元素



正如标题所述,如何删除任何给定XML文件的所有元素。 假设我们有以下 XML 文件:示例.xml:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:id="@+id/idExample">
<Button
android:id="@+id/beispiel2"
android:onClick="onSelectDas"
android:text="Check"
/>
<Button
android:id="@+id/beispiel2"
android:onClick="onSelectDas"
android:text="Check"
/>
</androidx.constraintlayout.widget.ConstraintLayout>

问题:如何从示例中删除两个按钮元素.xml - 以编程方式?

public static void removeDirectChildren( Node parent )
{
NodeList childNodes = parent.getChildNodes();
while ( childNodes.getLength() > 0 )
{
parent.removeChild( childNodes.item( 0 ) );
}
}

然后用根元素调用它。

ConstraintLayout上调用removeAllViews()

调用此方法以从 ViewGroup 中删除所有子视图。

contraintLayout.removeAllViews()

最新更新