【问题标题】:Get RecyclerView instance onCreateViewHolder to set params获取 RecyclerView 实例 onCreateViewHolder 设置参数
【发布时间】:2016-05-17 11:25:10
【问题描述】:

好的,伙计们,我需要找到一种方法来更改 RecyclerView 的方向更改时到顶部的距离,因为它在水平和垂直方面是不同的,我在项目 onBindViewHolder 上进行了这项工作,但我还需要设置参数对于 RecyclerView,以下代码不起作用:

public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    final View view = this.layoutInflater.inflate(R.layout.row_item, parent, false);
    // Create layout params for the RecyclerView
    RecyclerView.LayoutParams params
        = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                                           ViewGroup.LayoutParams.MATCH_PARENT);
    // Set them margins
    params.setMargins(0, spanCount * 500, 0, spanCount * 10);
    // Get reference, this doesn't work
    RecyclerView rv = (RecyclerView) parent.getChildAt(0); // Doesn't work
    rv.setLayoutParams(params); // <- Throws NPE
    return new ItemViewHolder(view);
}

我也尝试将 RecyclerView 投射到父级和视图,也没有工作。

【问题讨论】:

    标签: android android-layout android-recyclerview


    【解决方案1】:

    只需将 RecyclerView 的引用传递给适配器的构造函数即可。

    【讨论】:

    • 使用RelativeLayout.LayoutParams 类而不是RecyclerView.LayoutParams。
    【解决方案2】:

    如果你想更新 RecyclerView 的 LayoutParameters,它不应该在适配器中。 Fragment / Activity 必须处理方向变化并在需要时更新 LayoutParam。

    【讨论】:

      【解决方案3】:

      如果你想在屏幕方向改变时改变 RecyclerView 的布局,为什么不直接在onConfigurationChanged 中改变它呢?

      【讨论】:

        猜你喜欢
        • 2023-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多