Small RecyclerView XML feature

github logo ・1 min read

Did you know, that you can set RecyclerView layoutManager directly in XML, instead of always set RecyclerView layoutManager in the code?

Examples

Paste one of this attribute in your RecyclerView in XML.

For GridLayoutManager:
app:layoutManager="android.support.v7.widget.GridLayoutManager"

For LinearLayoutManager:
app:layoutManager="android.support.v7.widget.LinearLayoutManager"

And for StaggeredGridLayoutManager:
app:layoutManager="android.support.v7.widget.StaggeredGridLayoutManager"

twitter logo DISCUSS (3)
markdown guide
 

This is neat! I wonder if it'd work with a custom LayoutManager as well?

 

Hmmm...I didn't use a custom layout manager, so I can't say anything, but I think it should. If you going to do it, could you leave a result?

 

So it looks like you can; as long as your layout manager defines the 4 parameter constructor:

public YourLayoutManager(Context context, AttributeSet attrs, int defStyleAttr,int defStyleRes)

Then in the xml layout, you just have to fully qualify your LayoutManager, so mine was

com.corey.testrecyclerview.ThreeColumnGridLayoutManager

I just had my layout manager extend grid layout manager and set the column count to 3 when the layout manager is created.

Classic DEV Post from Mar 23

Thing's I've learned so far starting an open source project - March 2019

A collection of thoughts on what I have learned so far since starting my open source game "company" this year.

Ildarov profile image
I am an Android developer. I like reading books about kotlin or java. In free time, I contribute to my own pet projects. Also like math.
profile pic

Don't be a stranger

Create your DEV Profile