Set Margin on RecyclerView programmatically

天大地大妈咪最大 提交于 2020-06-08 07:12:47

问题


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

Here is my code:

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);

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.

Any help would be appreciated.


回答1:


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);



回答2:


for me, the parent of recyclerview is a constraintLayout,

        val margins = (rv.layoutParams as ConstraintLayout.LayoutParams).apply {
        leftMargin = 0
        rightMargin = 0
    }
    rv.layoutParams = margins

or it will get cast error, viewGroup.LayoutParams can't be cast to COnstarintLayout.LayoutParams




回答3:


You need use new object of 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();



回答4:


I am also facing this type of issue, Use below code to handle margin issue of 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);


来源:https://stackoverflow.com/questions/38985346/set-margin-on-recyclerview-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!