使UI元素相对于屏幕大小?

时间:2013-01-29 02:51:32

标签: android android-layout android-widget

让我们说我想用左右两列按钮制作相对视图。

每个按钮占据屏幕的20%,相隔10%,两侧保留边框。但要为任何屏幕尺寸执行此操作。 DP我觉得不行,因为你怎么知道每个不同屏幕上的DP像素数?

基本上你如何保持UI在所有设备之间相对相同和适合?

1 个答案:

答案 0 :(得分:1)

简短回答:LinearLayout

答案很长:

Defining a percentage width for a LinearLayout?

还有一些方法可以在运行时获得密度,但从长远来看,上述内容更容易。

准备好一些伪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>

编辑:

如果你想做很多动态调整大小,我有这个自定义类来获取屏幕大小:

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等)