使UI元素相对于屏幕尺寸? [英] Making UI elements relative to screen size?

查看:93
本文介绍了使UI元素相对于屏幕尺寸?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我想用左右两列按钮进行相对视图.

Lets say I wanted to make a relative view with two columns of buttons, left and right.

每个按钮正好占据屏幕的20%,相隔10%,其余边框在侧面.但是要针对任何屏幕尺寸进行此操作. DP我认为行不通,因为您如何知道每个不同屏幕上的DP像素数?

Where each button takes up exactly 20% of the screen, separated by 10%, with the remaining border on the sides. But to do this for any screen size. DP I think won't work because how do you know the DP pixel count on each different screen?

基本上,如何使UI在所有设备之间保持相对一致和合适?

Basically how do you keep UI's relatively the same and fitting between all devices?

推荐答案

简短答案:LinearLayout.

长答案在这里:

是为LinearLayout定义百分比宽度吗?

还有一些在运行时获取密度的方法,但是从长远来看,上述方法更容易.

There are also ways of getting density at runtime, but the above is easier in the long run.

准备一些伪xml!

<LinearLayout double fill parent, vertical>
    <RelativeLayout w = 0, h = 0, weight smallish>
         <Button A />
    </RelativeLayout>
    <LinearLayout w = 0, h = 0, weight largish. horizontal>
         <!-- maybe you want these to be RelativeLayout and set the buttons
         as centerHorizontalInParent="true" -->
         <LinearLayout w = 0, h = 0, weight whatever 20% is>
              <Buttons with some padding/margins>
         </LinearLayout>
         <Some kind of spacer, or just pad the LLs />
         <LinearLayout repeat above />
     </LL>
</LL>

如果您打算进行大量的动态调整大小,则可以使用以下自定义类来获取屏幕尺寸:

If you are bent on doing alot of dynamic resizing, I have this custom class for getting screen size:

public class ScreenGetter {
    private float pixHeight;
    private float pixWidth;
    private float dpHeight;
    private float dpWidth;
    private float density;

public ScreenGetter (Context context){
    Display display = ((WindowManager)
                context.getSystemService(Context.WINDOW_SERVICE))
                .getDefaultDisplay();
    DisplayMetrics metrics = new DisplayMetrics ();
    display.getMetrics(metrics);

    pixHeight = metrics.heightPixels;
    pixWidth = metrics.widthPixels;
    density  = context.getResources().getDisplayMetrics().density;
    dpHeight = pixHeight / density;
    dpWidth  = pixWidth / density;
}

public float getPixHeight(){return pixHeight;}
public float getPixWidth(){return pixWidth;}
public float getDpHeight(){return dpHeight;}
public float getDpWidth(){return dpWidth;}
public float getDensity(){return density;}

}

显然,您需要做一些数学运算才能弄清楚您想要的大小和密度不同的产品.您还需要考虑不使用的屏幕部分(ActionBar等)

Obviously you'll need to do some math to figure out what you want at different sizes and densities. You also need to account for parts of the screen you are not using (ActionBar, etc.)

这篇关于使UI元素相对于屏幕尺寸?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆