根据屏幕宽度制作视图的宽度 [英] Making a View's width based on screen width

查看:36
本文介绍了根据屏幕宽度制作视图的宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让视图的宽度基于屏幕的宽度.根据 0 到 100 之间的值,宽度将是屏幕宽度的百分比.这是我在 DP 中获取屏幕宽度的方法:

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;

这会为我的设备返回 360dp,这是正确的.然后我用它来设置我的视图的宽度,其中 timeCountNewRange() 返回一个 0 - 100 的值:

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

出于某种原因,当timeCountNewRange"值为 100 时,它仅为屏幕宽度的 60% 左右,其他所有内容也更短.如果替换

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

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(360, 15);

视图仍然只有屏幕宽度的 60% 左右.此错误因设备而异,具体取决于屏幕尺寸.如何根据屏幕宽度正确设置宽度?

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?

推荐答案

如果以编程方式设置,布局参数将以像素为单位设置.您将不得不再次将 dp 转换为像素并设置宽度

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

这篇关于根据屏幕宽度制作视图的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆