JBr*_*901 6 android android-layout
我是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);
}
Run Code Online (Sandbox Code Playgroud)
所以如果我说setSizeByRatio(Button,10,25); 它将按钮宽度设置为屏幕宽度的10%,高度设置为屏幕的25%.
是否有绝对布局不起作用的手机?此布局是否会导致任何其他问题?
不推荐使用AbsoluteLayout的原因是因为您在LinearLayout或GridLayout中有相同或更多的替代方法.您似乎正在尝试根据绝对位置和像素数计算位置,这种方法通常应该由于varoius屏幕尺寸和密度问题而避免.
阅读@amiekuser提供的链接,并关注理解最佳实践的方式.一些提示是为ldpi,mdpi和hdpi文件夹创建图像,使用单位表示dpi(密度无关像素)而不是原始像素,以及如何使用模拟器在多种屏幕尺寸和密度上测试应用程序.
编辑:
要设置视图的x和y位置,必须使用LayoutParams.请参阅此问题,了解如何使用LayoutParams为View设置TopMargin和LeftMargin.
| 归档时间: |
|
| 查看次数: |
5412 次 |
| 最近记录: |