Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Margin on RecyclerView programmatically

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.

like image 640
VIN Avatar asked Aug 16 '16 22:08

VIN


People also ask

How do I set the margins for RecyclerView programmatically?

margin); int marginTopPx = (int) (marginTopDp * getResources(). getDisplayMetrics(). density + 0.5f); layoutParams. setMargins(0, marginTopPx, 0, 0); recyclerView.

How do you set margin top programmatically?

Set LayoutParams to the view. To set margin to the view create LayoutParams instance, and set margin to the view. LinearLayout. LayoutParams layoutParams = new LinearLayout.

How do I set margin to dialog in android programmatically?

setWebViewClient(new MyWebViewClient()); webView. setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub dialog. dismiss(); } }); dialog. show();


2 Answers

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);
like image 194
Bharat Avatar answered Sep 19 '22 12:09

Bharat


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

like image 25
Xianwei Avatar answered Sep 20 '22 12:09

Xianwei