android - 如何设置 RecyclerView 应用程序 :layoutManager ="" from XML?

标签 android xml android-recyclerview androidx

如何设置RecyclerView来自 XML 的布局管理器?

    <android.support.v7.widget.RecyclerView
        app:layoutManager="???"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

最佳答案

您可以查看文档:

Class name of the Layout Manager to be used.

The class must extend androidx.recyclerview.widget.RecyclerViewView$LayoutManager and have either a default constructor or constructor with the signature (android.content.Context, android.util.AttributeSet, int, int)

If the name starts with a '.', application package is prefixed. Else, if the name contains a '.', the classname is assumed to be a full class name. Else, the recycler view package (androidx.appcompat.widget) is prefixed

使用 androidx,您可以使用:

<androidx.recyclerview.widget.RecyclerView
     xmlns:app="http://schemas.android.com/apk/res-auto"
     app:layoutManager="androidx.recyclerview.widget.GridLayoutManager">

通过支持库,您可以使用:

<android.support.v7.widget.RecyclerView
    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:layoutManager="android.support.v7.widget.GridLayoutManager" >

您还可以添加以下属性:

  • android:orientation = "horizo​​ntal|vertical":控制LayoutManager的方向(eg:LinearLayoutManager)
  • app:spanCount:设置GridLayoutManager
  • 的列数

例子:

<androidx.recyclerview.widget.RecyclerView
    app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
    app:spanCount="2"
    ...>

或:

<androidx.recyclerview.widget.RecyclerView
    app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
    android:orientation="vertical"
    ...>

您也可以使用 tools 命名空间(即 tools:orientationtools:layoutManager)添加它们然后它只会影响 IDE 预览,您可以继续在代码中设置这些值。

关于android - 如何设置 RecyclerView 应用程序 :layoutManager ="" from XML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35679776/

相关文章:

java - Recyclerview 不会对大型数据集进行动画处理

android - 如何在圆角布局上添加波纹效果?

java - 通过 GPS 坐标确定国家/地区

java - RemoveChild 删除具有该名称的第一个子项,但跳过下一个具有相同名称的子项

java - 尝试在 Java 中创建 XML 文件 - 获取 DOMException : HIERARCHY_REQUEST_ERR

java - 如何在Fragments中设置RecyclerView OnClickListener?

java - Activity.java中的多个选中项RecyclerView

android - Firebase 远程配置和 Microsoft Codepush 之间的区别

android - 在Android中制作带有缩略图的项目的丰富 ListView

java - 解析包含嵌套标签的 xml