Kaleb Kaleb - 1 year ago 511
Android Question

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

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

Any help would be appreciated.

Answer Source

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

ViewGroup.MarginLayoutParams marginLayoutParams = 
      (ViewGroup.MarginLayoutParams) mRecyclerView.getLayoutParams();
marginLayoutParams.setMargins(0, 10, 0, 10);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download