我希望我的RelativeLayouts的大小和位置与设备屏幕的大小无关(相对)。例如:
如果设备A 的屏幕宽度为480,高度为800且设备B 的屏幕宽度为720,高度为1280,则我的RelativeLayout必须为,例如,设备A 中的160宽度和267高度以及设备B中的240宽度和427高度。这很简单,只需获取屏幕宽度和高度,然后计算出您想要的百分比。这部分我用下面的代码做了,它正在工作:
int width = methodToGetScreenWidth();
relativeOneWidth = ((width / 100) * 90); // 90% of the screen width.
relativeOneHeight = (int) (relativeOneWidth / 1.75f);
relativeTwoWidth = (relativeOneWidth / 2);
relativeTwoHeight = (relativeOneHeight / 4);
relativeThreeWidth = (relativeOneWidth / 4);
relativeThreeHeight = (relativeOneHeight / 4);
它在我测试的所有设备上都运行良好。问题在于立场。我尝试了很多东西来计算边距,但是它并没有在每个设备中处于相同的位置(大多数情况下它非常接近所需的位置,但不是确切的位置)。这是我试过的:
relativeOneLeftMargin = ((width - relativeOneWidth) / 2); // The screen width - the relativeOne width / 2, it should returns the relativeOne left margin, shouldn't it?
relativeOneTopMargin = ((height - relativeOneHeight) / 2); // And this, the relativeOne top margin, right?
relativeTwoLeftMargin = (int) (relativeOneLeftMargin * 1.5f);
relativeTwoTopMargin = (int) (relativeOneTopMargin * 0.78f);
relativeThreeLeftMargin = relativeOneTopMargin + relativeOneHeight;
P.S。: relativeOne 位于屏幕中间:
relativeOne.addRule(RelativeLayout.CENTER_IN_PARENT);
我也尝试以这种方式获得边距,但它返回0:
relativeOne.getLeft();
relativeOne.getTop();
我真的不知道为什么它在所有设备中的位置不同。有什么建议吗?
答案 0 :(得分:1)
首先,在不同设备中使用定位时,建议使用DP(设备相关点)。您可以在http://developer.android.com/guide/practices/screens_support.html
了解如何使用它们使用时:
relativeOne.getLeft();
relativeOne.getTop();
您将始终获得0,因为在您进行此调用时,Android未完成绘制布局的父级,因此它没有关于其相对位置的信息。如果您想访问此信息,则必须在绘图后拨打电话。一种方法是使用类视图的方法发布:
parent.post(new Runnable() {
@Override
public void run() {
relativeOne.getLeft();
relativeOne.getTop();
}
});
这样,您可以在绘制布局后执行调用。
答案 1 :(得分:0)
我改变了这段代码:
relativeTwoLeftMargin = (int) (relativeOneLeftMargin * 1.5f);
relativeTwoTopMargin = (int) (relativeOneTopMargin * 0.78f);
对此:
relativeTwoLeftMargin = Math.round(relativeOneLeftMargin * 1.5f);
relativeTwoTopMargin = Math.round(relativeOneTopMargin * 0.78f);
现在它正在运作。我猜 int 强制转换没有返回确切的值。