代码之家  ›  专栏  ›  技术社区  ›  Blazej SLEBODA

android.support.v7.widget.recyclerview作为根视图

  •  0
  • Blazej SLEBODA  · 技术社区  · 6 年前

    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>
    
    2 回复  |  直到 6 年前
        1
  •  2
  •   navylover    6 年前

    正如官方文件所说:

    根元素可以是视图组、视图或 元素,但必须只有一个根元素,并且必须包含 具有android命名空间的xmlns: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>
    
        2
  •  0
  •   vishva kapadia    6 年前

    是的,您可以将recycleview作为活动的根元素。但是,将任何视图组作为根,将recycleview作为子视图是一种良好的做法。

    下面是代码:

    <android.support.v7.widget.RecyclerView 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent"
    android:orientation="vertical"
    app:layoutManager="android.support.v7.widget.LinearLayoutManager" />