Reputation: 5045
I am trying to let a View's width be based on the width of the screen. Depending on a value from 0 to 100, the width will be that percentage of the screen width. Here is how I am getting the screen width in DP:
Display display = ((Activity)context).getWindowManager().getDefaultDisplay();
DisplayMetrics outMetrics = new DisplayMetrics ();
display.getMetrics(outMetrics);
float density = context.getResources().getDisplayMetrics().density;
float screenWidthDP = outMetrics.widthPixels / density;
This returns 360dp for my device which is correct. I then use this to set the width of my view, where timeCountNewRange() returns a value from 0 - 100:
int timeCountNewRange = getNewRangeTimeCount(timeCount, min, max);
int widthDP = (int) (((double)timeCountNewRange / 100.0) * screenWidthDP);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(widthDP, 15);
params.setMargins(5, 0, 0, 0);
appHolder.timeBar.setLayoutParams(params);
For some reason, when the "timeCountNewRange" value is 100 it is only about 60% of the screen width, and everything else is shorter as well. If replace
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(widthDP, 15);
with
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(360, 15);
the view is still only around 60% of the screen width. This error differs from device to device based on screen size. How do I properly set the width to be based upon the screen width?
Upvotes: 5
Views: 1311
Reputation: 300
The layout params will be set in pixels if set programmatically. You will have to convert the dp to pixels again and set the width
Upvotes: 2