【发布时间】:2016-12-23 10:41:12
【问题描述】:
我需要以编程方式设置 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 不存在该方法。
任何帮助将不胜感激。
【问题讨论】:
-
您的
RecyclerView的父ViewGroup是什么? -
持有recyclerView的父级是
android.support.v4.widget.SwipeRefreshLayout。 -
如何将 recyclerview 包裹在类似线性布局的东西中,然后为线性布局设置边距?
-
虽然包装 recyclerView 有效,但为此目的添加额外的布局似乎很浪费。我接受了下面的答案,因为它可以工作并且不涉及仅为包装目的添加布局。
标签: android android-recyclerview layoutparams