How to set Layoutparams height/width in dp value?
When you specify values programmatically in the LayoutParams
, those values are expected to be pixels.
To convert between pixels and dp you have to multiply by the current density factor. That value is in the DisplayMetrics
, that you can access from a Context
:
float pixels = dp * context.getResources().getDisplayMetrics().density;
So in your case you could do:
.
.
float factor = holder.itemView.getContext().getResources().getDisplayMetrics().density;
params.width = (int)(item.getWidth() * factor);
params.height = (int)(item.getHeight() * factor);
.
.
I believe you should be using a dp value defined in dimens along with getDimensionPixelSize. In a custom view, the Kotlin implementation would look like:
val layoutParams = layoutParams
val width = context.resources.getDimensionPixelSize(R.dimen.width_in_dp)
layoutParams.width = width