【问题标题】:Get RecyclerView orientation in custom view在自定义视图中获取 RecyclerView 方向
【发布时间】:2018-06-13 15:28:33
【问题描述】:

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

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

有可能吗?

我知道RecyclerView 的方向是在其LayoutManager 中定义的。或许是不可能得到这个LayoutManager的信息?

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

【问题讨论】:

    标签: java android android-recyclerview android-custom-view


    【解决方案1】:

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

    (recyclerView.layoutManager as LinearLayoutManager).orientation
    

    它返回LinearLayout.HORIZONTALLinearLayout.VERTICAL

    【讨论】:

      【解决方案2】:

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

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

      如果 recyclerView 分别为 HORIZONTALVERTICAL

      ,则此行返回 01

      以防万一,这是我的 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");
           }
      

      【讨论】:

        【解决方案3】:

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

        来自文档

          Returns the current orientation of the layout.
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-02-09
          • 1970-01-01
          • 2017-07-20
          相关资源
          最近更新 更多