Set Margin on RecyclerView programmatically

前端 未结 4 764
旧巷少年郎
旧巷少年郎 2021-01-12 00:13

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.Cla

相关标签:
4条回答
  • 2021-01-12 00:50

    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();
    
    0 讨论(0)
  • 2021-01-12 00:53

    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);
    
    0 讨论(0)
  • 2021-01-12 01:00

    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);
    
    0 讨论(0)
  • 2021-01-12 01:04

    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

    0 讨论(0)
提交回复
热议问题