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?

Add Comment
2 Answer(s)
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.

Add Comment

Call removeAllViews() on the ConstraintLayout.

Call this method to remove all child views from the ViewGroup.

contraintLayout.removeAllViews() 
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.