首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >安卓: AbsoluteLayout?

安卓: AbsoluteLayout?
EN

Stack Overflow用户
提问于 2012-03-15 16:32:49
回答 2查看 5.5K关注 0票数 6

我是Android的新手。我喜欢在任何我想要的地方自由地放置绘图对象。所以我一直在使用绝对布局。我收到一条消息,告诉我要使用不同的布局。我读到这是因为不同手机的分辨率不同。我的问题是,这是不使用绝对布局的唯一原因吗?我提出了一种使用度量来调整像素的方法。

代码语言:javascript
复制
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%。

有没有绝对布局不起作用的手机?这种布局是否会导致其他问题?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-03-15 17:21:17

不推荐使用AbsoluteLayout的原因是,您可以在LinearLayout或GridLayout中使用其他方法来完成相同或更多的操作。您似乎正在尝试根据绝对位置和像素数来计算位置,由于可变屏幕大小和密度的问题,通常应该避免这种方法。

阅读@amiekuser提供的链接,重点了解最佳实践是如何实现的。一些提示是为ldpi,mdpi和hdpi文件夹创建图像,使用dpi (密度无关像素)而不是原始像素的单位,以及如何使用仿真器在多种屏幕尺寸和密度上测试您的应用程序。

编辑:

要设置视图的x和y位置,必须使用LayoutParams。有关如何使用this question设置视图的TopMargin和LeftMargin的信息,请参阅LayoutParams。

票数 6
EN

Stack Overflow用户

发布于 2012-03-15 16:47:10

安卓手机有许多外形规格,不仅在屏幕尺寸(2.7英寸,3.2英寸,3.7英寸)方面差异很大,而且在分辨率(480X800,480X848等)方面也有很大差异。谷歌自己建议不要使用AbsoluteLayout。事实上,它在较新的应用编程接口版本中已被弃用。

下面的链接详细解释了所有这些内容:

http://developer.android.com/guide/practices/screens_support.html

请查看最佳实践部分。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9716197

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档