Android:AbsoluteLayout?

我是 Android新手.我喜欢在任何我想要的地方拥有自由范围的绘图对象.所以我一直在使用Absolute Layout.我收到一条消息,说要使用不同的布局.而且我已经读到这是因为不同手机的不同分辨率.我的问题是,这是不使用绝对布局的唯一原因吗?我制作了一个使用指标来调整像素的方法.
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中有相同或更多的替代方法.您似乎正在尝试根据绝对位置和像素数计算位置,这种方法通常应该由于varoius屏幕尺寸和密度问题而避免.

阅读@amiekuser提供的链接,并关注理解最佳实践的方式.一些提示是为ldpi,mdpi和hdpi文件夹创建图像,使用单位表示dpi(密度无关像素)而不是原始像素,以及如何使用模拟器在多种屏幕尺寸和密度上测试应用程序.

编辑:

要设置视图的x和y位置,必须使用LayoutParams.请参阅this question,了解如何使用LayoutParams为View设置TopMargin和LeftMargin.

相关文章

文章浏览阅读8.8k次,点赞9次,收藏20次。本文操作环境:win1...
文章浏览阅读1.2w次,点赞15次,收藏69次。实现目的:由main...
文章浏览阅读3.8w次。前言:最近在找Android上的全局代理软件...
文章浏览阅读2.5w次,点赞17次,收藏6次。创建项目后,运行项...
文章浏览阅读8.9w次,点赞4次,收藏43次。前言:在Android上...
文章浏览阅读1.1w次,点赞4次,收藏17次。Android Studio提供...