gpt4 book ai didi

android - 使 UI 元素相对于屏幕尺寸?

转载 作者:行者123 更新时间:2023-11-30 03:48:22 27 4
gpt4 key购买 nike

比方说我想用左右两列按钮创建一个相对 View 。

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

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

最佳答案

简答: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 等)

关于android - 使 UI 元素相对于屏幕尺寸?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14574875/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com