Set a view's width to be relative to device screen programmatically

74 Views Asked by At

I have a horizontal RecyclerView with child elements which I want to change the width of to be a bit less than the current match_parent set via the layout. I want to do this so that the next element in list is a bit visible on screen.

In the adapter onCreateViewHolder I am doing this:

ViewGroup.LayoutParams params = view.getLayoutParams();
params.width = MainActivity.deviceWidth - (int) MainActivity.dpToPx(40.0f);
view.setLayoutParams(params);

where MainActivity.deviceWidth is:

DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
deviceWidth = displaymetrics.widthPixels;
screenDensity = Resources.getSystem().getDisplayMetrics().density;

and dpToPx is this function:

public static float dpToPx(float dp) {
    return (dp * screenDensity + 0.5f);
}

This works. however, I noticed that on different devices, the "margin" I am setting is not always the same. I.e. the next card in the RecyclerView is not always showing the same amount.

Is the dpToPx conversion correct? I might be missing something else in my calculation but I am not sure what.

Update

Changing:

params.width = MainActivity.deviceWidth - (int) MainActivity.dpToPx(40.0f);

To:

params.width = (int) (MainActivity.deviceWidth *0.9);

works!. I am fine with this solution. I just want to know why the previous one does not work...

0

There are 0 best solutions below