Search code examples
javaandroidlayoutroot

Add toolbar to activity with a listView


I'm trying to add a toolbar to my activity, which has only a list of elements as content. This is my code, but it doesn't works because it says that I'm using multiple root. How is it possible?

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:textSize="20sp" >
</TextView>

<android.support.v7.widget.Toolbar
  android:id="@+id/my_toolbar"
  android:layout_width="match_parent"
  android:layout_height="?attr/actionBarSize"
  style="@style/HeaderBar"
  app:theme="@style/ActionBarThemeOverlay"
  app:popupTheme="@style/ActionBarPopupThemeOverlay"
  android:elevation="4dp"/>

Solution

  • You need to put all that inside a RelativeLayout or LinearLayout.

    In this example i use RelativeLayout

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout 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">
    
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:textSize="20sp" 
        android:layout_below=""@+id/my_toolbar/>
    
    
    <android.support.v7.widget.Toolbar
        android:id="@+id/my_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        style="@style/HeaderBar"
        app:theme="@style/ActionBarThemeOverlay"
        app:popupTheme="@style/ActionBarPopupThemeOverlay"
        android:elevation="4dp"/>
    
    </RelativeLayout>
    

    In case the toolbar is not a the top just add in the Toolbar part android:layout_alignParentTop="true"