NayMak
NayMak

Reputation: 178

Get RecyclerView orientation in custom view

I'm trying to create a custom view extending RecyclerView. In my custom view, I have some things to do according to the RecyclerView orientation (horizontal or vertical).

Unfortunately, I don't find any way to know and get the RecyclerView orientation.

Is it even possible to do?

I know that RecyclerView orientation is defined in its LayoutManager. Maybe it is impossible to get this LayoutManager information?

Thank you in advance for any help you can provide.

Upvotes: 1

Views: 2202

Answers (3)

Cafer Mert Ceyhan
Cafer Mert Ceyhan

Reputation: 1766

If your layout manager is LinearLayoutManager, then you can use this function.

(recyclerView.layoutManager as LinearLayoutManager).orientation

It returns LinearLayout.HORIZONTAL or LinearLayout.VERTICAL

Upvotes: 6

NayMak
NayMak

Reputation: 178

Ok I just found the solution:

LayoutManager.getProperties(context, attrs, 0, 0).orientation

This line returns either 0 or 1 if the recyclerView is respectively HORIZONTAL or VERTICAL

Just in case, here is my customView constructor:

     public CustomRecyclerView(Context context, AttributeSet attrs) {
            super(context, attrs);

            if (LayoutManager.getProperties(context, attrs, 0, 0).orientation == 0)
                Log.d("recycler orientation", "horizontal");
            else if (LayoutManager.getProperties(context, attrs, 0, 0).orientation == 1)
                Log.d("recycler orientation", "vertical");
     }

Upvotes: 2

Blackbelt
Blackbelt

Reputation: 157487

Unless you have a custom LayoutManager, the orientation info makes sense only for LinearLayoutManager and its subclasses (GridLayoutManager). In this case you can use the LinearLayoutManager.getOrientation method.

From the doc

  Returns the current orientation of the layout.

Upvotes: 0

Related Questions