Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/231.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 相对尺寸和位置(边距)_Android - Fatal编程技术网

Android 相对尺寸和位置(边距)

Android 相对尺寸和位置(边距),android,Android,我希望我的RelativeLayouts的大小和位置与设备屏幕的大小无关(相对)。例如: 如果设备A的屏幕宽度为480,高度为800,设备B的屏幕宽度为720,高度为1280,那么我的RelativeLayout必须具有,例如,设备A的屏幕宽度为160,高度为267,设备B的屏幕宽度为240,高度为427。很简单,只需获取屏幕宽度和高度,然后计算所需的百分比。我用下面的代码完成了这一部分,它正在工作: int width = methodToGetScreenWidth(); relative

我希望我的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.addRule(RelativeLayout.CENTER_IN_PARENT);
我也尝试通过这种方式获取边距,但它返回0:

relativeOne.getLeft();
relativeOne.getTop();

我真的不知道为什么它在所有设备中都不处于相同的位置。有什么建议吗?

首先,在不同设备中使用定位时,建议使用DP(设备相关点)。你可以在网站上看到如何使用它们

使用时:

relativeOne.getLeft();
relativeOne.getTop();
您将始终得到0,因为在您进行此调用时,Android尚未完成布局的父级绘制,因此它没有关于其相对位置的信息。如果要访问此信息,必须在绘图后进行调用。一种方法是使用类视图的方法post:

parent.post(new Runnable() {
            @Override
            public void run() {
                relativeOne.getLeft();
                relativeOne.getTop();
            }
        });
这样,您可以在绘制布局后执行调用。

我更改了以下代码:

relativeTwoLeftMargin = (int) (relativeOneLeftMargin * 1.5f);
relativeTwoTopMargin = (int) (relativeOneTopMargin * 0.78f);
对于这一点:

relativeTwoLeftMargin = Math.round(relativeOneLeftMargin * 1.5f);   
relativeTwoTopMargin = Math.round(relativeOneTopMargin * 0.78f);
现在它开始工作了。我猜int cast没有返回准确的值