Search code examples
androidandroid-relativelayout

creating new view while running in relative layout (middle of the layout)


I have an XML file like this and I want with pressing the "+" button, the user shall be able to add more names, addresses, etc to the form. [like most web forms on Internet that have "Add more" button]

In java code, I'm using this codes for creating new textview while running, but my problem is that all samples that I found is for an empty relative layout. So I'm trying to create a new textview in middle of layout and I need the views after new view to shift down.

If I want to change every single view, my code will be so long, and it's not appropriate, I think.

How can I do this? This is my relative layout:

enter image description here


Solution

  • Begin by having a layout like so:

    <LinearLayout android:id="@+id/root">
      <LinearLayout android:id="@+id/name_container">
          <Button android:id="@+id/add_name" />
      </LinearLayout>
      <LinearLayout android:id="@+id/address_container">
          <Button android:id="@+id/add_address"
      </LinearLayout>  
    </LinearLayout>  
    

    Now, each of these "containers" will contain EditText of respective type. For example, name_container will contain EditText for names, and so on.

    Whenever a user clicks on a particular button, just inflate a view of the appropriate type and add it to the corresponding container. If you want to animate the addition / removal of views, use android:animateLayoutChanges="true"

    This way, you are adding views "in the middle" of the layout. Android will handle the animation and redrawing for you without having to write any code.