Android: How to delete all the Elements of a XML-File programmatically
as the title states, how to delete all the elements of any given XML-File. Let’s say we have the following XML-File: example.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>
Question: How to delete two Button Elements from the example.xml – programmtically?
public static void removeDirectChildren( Node parent ) { NodeList childNodes = parent.getChildNodes(); while ( childNodes.getLength() > 0 ) { parent.removeChild( childNodes.item( 0 ) ); } }
and you call it with the root element.
Call removeAllViews()
on the ConstraintLayout.
Call this method to remove all child views from the ViewGroup.
contraintLayout.removeAllViews()