我需要以编程方式在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
不存在该方法。
任何帮助都将不胜感激。
答案 0 :(得分:16)
试一试。您可以参考this了解更多信息。
ViewGroup.MarginLayoutParams marginLayoutParams =
(ViewGroup.MarginLayoutParams) mRecyclerView.getLayoutParams();
marginLayoutParams.setMargins(0, 10, 0, 10);
mRecyclerView.setLayoutParams(marginLayoutParams);
答案 1 :(得分:1)
您需要使用MargingLayoutParams的新对象
final FrameLayout.MarginLayoutParams marginLayoutParams = new
FrameLayout.MarginLayoutParams(rvContacts.getLayoutParams());
marginLayoutParams.leftMargin = left;
marginLayoutParams.topMargin = top;
marginLayoutParams.rightMargin = right;
marginLayoutParams.bottomMargin = bottom;
recyclerView.setLayoutParams(marginLayoutParams);
recyclerView.requestLayout();
答案 2 :(得分:0)
对我来说,recyclerview
的父母是constraintLayout
,
val margins = (rv.layoutParams as ConstraintLayout.LayoutParams).apply {
leftMargin = 0
rightMargin = 0
}
rv.layoutParams = margins
否则将发生转换错误,viewGroup.LayoutParams无法转换为COnstarintLayout.LayoutParams
答案 3 :(得分:0)
我也面临此类问题,请使用下面的代码来处理recyclerview的保证金问题。
ViewGroup.MarginLayoutParams marginLayoutParams=
(ViewGroup.MarginLayoutParams) recyclerView.getLayoutParams();
// here i try to set only top margin, Get dimension from dimension file.
int topMargin = getResources()
.getDimensionPixelSize(R.dimen.top_margin);
marginLayoutParams.setMargins(marginLayoutParams.getMarginStart(),
topMargin, marginLayoutParams.getMarginEnd(), marginLayoutParams.bottomMargin);
recyclerView.setLayoutParams(marginLayoutParams);