在自定义视图中获取 RecyclerView 方向

Get RecyclerView orientation in custom view

我正在尝试创建扩展 RecyclerView 的自定义视图。在我的自定义视图中,我需要根据 RecyclerView 方向(水平或垂直)做一些事情。

不幸的是,我找不到任何方法来了解和获取 RecyclerView 方向。

甚至可以做到吗?

我知道 RecyclerView 方向在其 LayoutManager 中定义。可能无法得到这个LayoutManager信息?

提前感谢您提供的任何帮助。

除非您有自定义 LayoutManager,否则方向信息仅对 LinearLayoutManager 及其子类 (GridLayoutManager) 有意义。在这种情况下,您可以使用 LinearLayoutManager.getOrientation 方法。

来自文档

  Returns the current orientation of the layout.

好的,我刚找到解决方案:

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

这一行 returns 如果 recyclerView 分别是 01 HORIZONTAL垂直

以防万一,这是我的 customView 构造函数:

     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");
     }

如果你的布局管理器是LinearLayoutManager,那么你可以使用这个函数。

(recyclerView.layoutManager as LinearLayoutManager).orientation

它returnsLinearLayout.HORIZONTALLinearLayout.VERTICAL