我需要以编程方式在 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);
如果我使用 ViewGroup.LayoutParams layoutParams = recyclerView.getLayoutParams
如堆栈跟踪所示,我不能再调用 setMargin
因为该方法不存在 ViewGroup.LayoutParams
任何帮助,将不胜感激。
原文由 VIN 发布,翻译遵循 CC BY-SA 4.0 许可协议
试试这个。您可以参考 此 以获取更多信息。