以编程方式在RecyclerView上设置保证金 [英] Set Margin on RecyclerView programmatically

查看:82
本文介绍了以编程方式在RecyclerView上设置保证金的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以编程方式在RecyclerView上设置上边距,但出现此异常:

I need to set the top margin on a RecyclerView programmatically, but I get this exception:

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不存在该方法.

If I use the ViewGroup.LayoutParams layoutParams = recyclerView.getLayoutParams as the stack trace suggests, I cannot call setMargin anymore as that method does not exist for ViewGroup.LayoutParams.

任何帮助将不胜感激.

推荐答案

尝试一下.您可以参考以获取更多信息.

Try this out. You can refer to this for more info.

ViewGroup.MarginLayoutParams marginLayoutParams = new ViewGroup.MarginLayoutParams(mRecyclerView.getLayoutParams());
marginLayoutParams.setMargins(0, 10, 0, 10);
mRecyclerView.setLayoutParams(marginLayoutParams);

这篇关于以编程方式在RecyclerView上设置保证金的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆