以编程方式在RecyclerView上设置保证金

VIN*_*VIN 8 android layoutparams android-recyclerview

我需要以编程方式在RecyclerView上设置上边距,但我得到以下异常:

java.lang.RuntimeException: Unable to resume activity java.lang.ClassCastException: android.view.ViewGroup$LayoutParams cannot be cast to android.support.v7.widget.RecyclerView$LayoutParams

这是我的代码:

RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams)recyclerView.getLayoutParams();
int marginTopDp = (int)getResources().getDimension(R.dimen.margin);
int marginTopPx = (int) (marginTopDp * getResources().getDisplayMetrics().density + 0.5f);
layoutParams.setMargins(0, marginTopPx, 0, 0);
recyclerView.setLayoutParams(layoutParams);
Run Code Online (Sandbox Code Playgroud)

如果我使用ViewGroup.LayoutParams layoutParams = recyclerView.getLayoutParams堆栈跟踪建议,我不能再调用setMargin因为该方法不存在ViewGroup.LayoutParams.

任何帮助,将不胜感激.

小智 18

试试吧.您可以参考获取更多信息.

ViewGroup.MarginLayoutParams marginLayoutParams = new ViewGroup.MarginLayoutParams(mRecyclerView.getLayoutParams());
marginLayoutParams.setMargins(0, 10, 0, 10);
mRecyclerView.setLayoutParams(marginLayoutParams);
Run Code Online (Sandbox Code Playgroud)

  • android.view.ViewGroup $ LayoutParams无法强制转换为android.view.ViewGroup $ MarginLayoutParams (10认同)
  • mRecyclerView.requestLayout(); 需要应用更改 (2认同)

Xia*_*wei 7

对我来说, 的父级recyclerview是 a constraintLayout,

        val margins = (rv.layoutParams as ConstraintLayout.LayoutParams).apply {
        leftMargin = 0
        rightMargin = 0
    }
    rv.layoutParams = margins
Run Code Online (Sandbox Code Playgroud)

否则会出现强制转换错误,viewGroup.LayoutParams 无法强制转换为 COnstarintLayout.LayoutParams