我需要以编程方式在 RecyclerView 上设置上边距,但出现此异常:
java.lang.RuntimeException:无法恢复 Activity java.lang.ClassCastException:android.view.ViewGroup$LayoutParams 无法转换为 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
.
如有任何帮助,我们将不胜感激。
最佳答案
试试这个。可以引用this了解更多信息。
ViewGroup.MarginLayoutParams marginLayoutParams = new ViewGroup.MarginLayoutParams(mRecyclerView.getLayoutParams());
marginLayoutParams.setMargins(0, 10, 0, 10);
mRecyclerView.setLayoutParams(marginLayoutParams);
关于android - 以编程方式在 RecyclerView 上设置边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38985346/