0

I cannot seem to find the right keywords for my question. Not to be confused with XML Layout editing, can I programmatically shift one View under another View in real-time inside a LinearLayout container?

Here is my main layout XML file. It is as easy as just dragging the two buttons to the UI editor and naming them:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:background="#000000"
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button 1" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button 2" />
</LinearLayout>

Let's say I did something in my app and suddenly button1 shifted below button2 and button2 went up. How can I make that happen? Does something like my1Button.shiftDown(); or similar even exist?

IOviSpot
  • 358
  • 3
  • 19
  • You can simply set the visibility visible or gone programetically – Rohit Suthar Oct 30 '19 at 17:26
  • You could do a `removeView` followed by an `addView` to specify the order, but depending on the effect you want you may be better off using a `RecyclerView`, as it has better support for dragging/dropping views – PPartisan Oct 30 '19 at 17:27
  • @RohitSuthar Could you clarify, please? @PPartisan I don't care about effects. A simple insta-shift is fine, so I'm not gonna bother with `RecyclerView`. – IOviSpot Oct 30 '19 at 17:28
  • In that case, you can follow the advice here: https://stackoverflow.com/questions/17776306/change-order-of-views-in-linear-layout-android – PPartisan Oct 30 '19 at 17:29
  • Whether you want to totally hide the button1 below the button2? – Rohit Suthar Oct 30 '19 at 17:29

1 Answers1

1

You would need to work with the children of the linear layout. Something like this:

public void reorderButtons() {
    LinearLayout layout = (LinearLayout) findViewById(R.id.main_layout);

    View button1 = layout.getChildAt(0);
    View button2 = layout.getChildAt(1);

    // Remove both buttons
    layout.removeAllViews();

    // Add the buttons in the order you want
    layout.addView(button2);
    layout.addView(button1);
}