2

假设我想用左右两列按钮制作一个相对视图。

每个按钮恰好占据屏幕的 20%,相隔 10%,其余边框位于两侧。但是要对任何屏幕尺寸执行此操作。DP 我认为行不通,因为你怎么知道每个不同屏幕上的 DP 像素数?

基本上,您如何保持 UI 相对相同并适合所有设备?

4

1 回答 1

1

简短的回答:LinearLayout

长答案在这里:

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

于 2013-01-29T02:54:28.150 回答