首页 > 解决方案 > android.support.v7.widget.RecyclerView 作为根视图

问题描述

android.support.v7.widget.RecyclerView 可以是布局文件中的根视图,还是我必须将其添加为“RelativeLayout”元素的子级?

布局 A

  <android.support.v7.widget.RecyclerView
      android:id="@+id/itemsRecyclerView"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      app:layoutManager="android.support.v7.widget.GridLayoutManager"
      app:spanCount="2"/>

布局 B

<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"
                tools:context=".ui.activity.MainActivity">

  <android.support.v7.widget.RecyclerView
      android:id="@+id/itemsRecyclerView"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      app:layoutManager="android.support.v7.widget.GridLayoutManager"
      app:spanCount="2"/>

</RelativeLayout>

标签: androidandroid-layout

解决方案


正如官方文档所说:

根元素可以是 ViewGroup、View 或元素,但必须只有一个根元素,并且它必须包含 xmlns:android 属性和 android 命名空间,如图所示。

所以你可以使用 RecyclerView 作为根视图:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >


</android.support.v7.widget.RecyclerView>

推荐阅读