我是Android的新手。我喜欢在任何我想要的地方自由地放置绘图对象。所以我一直在使用绝对布局。我收到一条消息,告诉我要使用不同的布局。我读到这是因为不同手机的分辨率不同。我的问题是,这是不使用绝对布局的唯一原因吗?我提出了一种使用度量来调整像素的方法。
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%。
有没有绝对布局不起作用的手机?这种布局是否会导致其他问题?
发布于 2012-03-15 17:21:17
不推荐使用AbsoluteLayout的原因是,您可以在LinearLayout或GridLayout中使用其他方法来完成相同或更多的操作。您似乎正在尝试根据绝对位置和像素数来计算位置,由于可变屏幕大小和密度的问题,通常应该避免这种方法。
阅读@amiekuser提供的链接,重点了解最佳实践是如何实现的。一些提示是为ldpi,mdpi和hdpi文件夹创建图像,使用dpi (密度无关像素)而不是原始像素的单位,以及如何使用仿真器在多种屏幕尺寸和密度上测试您的应用程序。
编辑:
要设置视图的x和y位置,必须使用LayoutParams。有关如何使用this question设置视图的TopMargin和LeftMargin的信息,请参阅LayoutParams。
发布于 2012-03-15 16:47:10
安卓手机有许多外形规格,不仅在屏幕尺寸(2.7英寸,3.2英寸,3.7英寸)方面差异很大,而且在分辨率(480X800,480X848等)方面也有很大差异。谷歌自己建议不要使用AbsoluteLayout。事实上,它在较新的应用编程接口版本中已被弃用。
下面的链接详细解释了所有这些内容:
http://developer.android.com/guide/practices/screens_support.html
请查看最佳实践部分。
https://stackoverflow.com/questions/9716197
复制相似问题