Android 我想在activity.java文件中使用工具栏,该工具栏必须位于layout.xml文件中,该文件仅包含ListView。我该怎么办?

Android 我想在activity.java文件中使用工具栏,该工具栏必须位于layout.xml文件中,该文件仅包含ListView。我该怎么办?,android,Android,我尝试了下面的xml。但我得到一个错误,指出“AdapterView中不支持addView(View,LayoutParams)” 您应该这样做: <?xml version="1.0" encoding="utf-8"?> <ListView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height=

我尝试了下面的xml。但我得到一个错误,指出“AdapterView中不支持addView(View,LayoutParams)”


您应该这样做:

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/categoriesLayout"
android:drawSelectorOnTop="true">

<android.support.v7.widget.Toolbar
    android:id="@+id/my_toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:elevation="4dp"
    android:theme="@style/ThemeOverlay.AppCompat.ActionBar"/>

</ListView>

由于
列表视图
不是
视图组
,因此会出现该错误。它不能保存在另一个视图中,如
视图组
-
线性布局
框架布局
等。您应该执行以下操作:

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/categoriesLayout"
android:drawSelectorOnTop="true">

<android.support.v7.widget.Toolbar
    android:id="@+id/my_toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:elevation="4dp"
    android:theme="@style/ThemeOverlay.AppCompat.ActionBar"/>

</ListView>


由于
列表视图
不是
视图组
,因此会出现该错误。它不能保存在另一个视图中,如
视图组
-
线性布局
框架布局
等。

谢谢。。我刚刚尝试了上面的xml,它正在工作。没问题,很高兴编码)谢谢。。我刚刚尝试了上面的xml,它正在工作。没问题,编码愉快)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar
        android:id="@+id/my_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:elevation="4dp"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar" />

    <ListView
        android:id="@+id/categoriesLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:drawSelectorOnTop="true"
        android:orientation="vertical" />

</LinearLayout>