簡體   English   中英

使用listView將工具欄添加到活動中

[英]Add toolbar to activity with a listView

我正在嘗試向活動添加工具欄,該工具欄僅包含一個元素列表作為內容。 這是我的代碼,但是因為它說我正在使用多個根,所以它不起作用。 這怎么可能?

<?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"/>

是的。Android是正確的。

只能有一個根目錄布局。 您可以添加相對布局或linearlayout作為根布局。 根目錄布局將包裝您的textview和工具欄。

謝謝

您需要將所有內容放入RelativeLayout或LinearLayout中。

在此示例中,我使用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>

如果工具欄不是頂部,只需在工具欄部分中添加android:layout_alignParentTop="true"

您正在嘗試在ListView項布局中添加Toolbar
您必須在Activity布局中添加Toolbar

您應該這樣:

<androidx.coordinatorlayout.widget.CoordinatorLayout>

        <com.google.android.material.appbar.AppBarLayout>

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:popupTheme="@style/AppTheme.PopupOverlay"
                />

        </com.google.android.material.appbar.AppBarLayout>

        <android.widget.ListView/>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

另外,您應該使用androidx庫而不是支持庫(例如androidx.appcompat.widget.Toolbar而不是android.support.v7.widget.Toolbar )和RecyclerView而不是ListView

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM