我是安卓新手。我喜欢在任何我想要的地方自由地绘制对象。所以我一直在使用绝对布局。我收到一条消息,要求使用不同的布局。我读到这是因为不同手机的分辨率不同。我的问题是,这是不使用绝对布局的唯一原因吗?我制定了一种使用指标来调整像素的方法。
public int widthRatio(double ratioIn){
DisplayMetrics dm = new DisplayMetrics(); //gets screen properties
getWindowManager().getDefaultDisplay().getMetrics(dm);
double screenWidth = dm.widthPixels; //gets screen height
double ratio = screenWidth/100; //gets the ratio in terms of %
int displayWidth = (int)(ratio*ratioIn); //multiplies ratio desired % of screen
return displayWidth;
}
//method to get height or Ypos that is a one size fits all
public int heightRatio(double ratioIn){
DisplayMetrics dm = new DisplayMetrics(); //gets screen properties
getWindowManager().getDefaultDisplay().getMetrics(dm);
double screenHeight = dm.heightPixels; //gets screen height
double ratio = screenHeight/100; //gets the ratio in terms of %
int newHeight = (int)(ratio*ratioIn); //multiplies ratio by desired % of screen
return newHeight;
}
//sets size of any view (button, text, ...) to a one size fits all screens
public void setSizeByRatio(View object, int width, int height){
LayoutParams params = object.getLayoutParams();
params.width = widthRatio(width);
params.height = heightRatio(height);
}
所以如果我说 setSizeByRatio(Button, 10, 25);它将按钮的宽度设置为屏幕宽度的 10%,高度设置为屏幕的 25%。
是否存在绝对布局无法使用的手机?这种布局会导致任何其他问题吗?
AbsoluteLayout 被弃用的原因是因为您可以在 LinearLayout 或 GridLayout 中找到具有相同功能甚至更多功能的替代方案。您似乎正在尝试根据绝对位置和像素数来计算位置,由于各种屏幕尺寸和密度的问题,通常应该避免这种方法。
阅读 @amiekuser 提供的链接,重点了解最佳实践。一些提示是为 ldpi、mdpi 和 hdpi 文件夹创建图像,使用 dpi(密度独立像素)单位而不是原始像素,以及如何使用模拟器在多种屏幕尺寸和密度上测试您的应用程序。
Edit:
要设置视图的 x 和 y 位置,您必须使用 LayoutParams。看这个问题 https://stackoverflow.com/questions/3294590/set-the-absolute-position-of-a-view-in-android关于如何使用 LayoutParams 设置视图的 TopMargin 和 LeftMargin。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)