Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

android - How to set RecyclerView app:layoutManager="" from XML?

How to set RecyclerView layoutManager from XML?

    <android.support.v7.widget.RecyclerView
        app:layoutManager="???"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As you can check in the doc:

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

With androidx you can use:

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

With the support libraries you can use:

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

Also you can add these attributes:

  • android:orientation = "horizontal|vertical": to control the orientation of the LayoutManager (eg:LinearLayoutManager)
  • app:spanCount: to set the number of columns for GridLayoutManager

Example:

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

or:

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

You can also add them using the tools namespace (i.e. tools:orientation and tools:layoutManager) and then it only impacts the IDE preview and you can continue setting those values in code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...