Search code examples
androidandroid-layoutandroid-linearlayout

Android placing a view above another


I have in my screen 5 components: space, listview, space, listview and space, as shown in the left image.

I want to be able to place another space (in red) above all of these components mentioned. All of them are lying inside a LinearLayout.

I tried to use another LinearLayout (with the space) inside the root LinearLayout, but it only caused bugs.

enter image description here

<?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="#009900"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.myname.appname.NameActivity">

<Space
    android:id="@+id/space1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#FFFFFF"
    android:layout_weight="0.5" />

<ListView
    android:id="@+id/listView1"
    android:layout_width="125dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:background="#00CC00"
    android:divider="#009900"
    android:dividerHeight="10dp"
    android:footerDividersEnabled="false"
    android:gravity="center"
    android:scrollbars="none" />


<Space
    android:id="@+id/space2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#FFFFFF"
    android:layout_weight="0.5" />

<ListView
    android:id="@+id/listView2"
    android:layout_width="124dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:background="#e6e600"
    android:divider="#009900"
    android:dividerHeight="10dp"
    android:gravity="center"
    android:scrollbars="none" />

<Space
    android:id="@+id/space3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#FFFFFF"
    android:layout_weight="0.5" />

</LinearLayout>

Solution

  • With what you have there, you need a nested linear layout to hold everything. It will look like this:

    <LinearLayout orientation="vertical">
    -- put your top container here --
    -- put your existing linearlayout AND its contents here --
    </LinearLayout>
    

    The outer container will be vertically oriented, while the second one will be horizontal, like you already have it.