[英]Set Views Y position programmatically
I got a layout in which there's a RelativeLayout
with a visibility of GONE
. 我有一个布局,其中有一个RelativeLayout
,其可见性为GONE
。 This rl is a layout for a bar with buttons which appears at the bottom of the fragment when setting the visibility to visible
. 此rl是带按钮的条的布局,当将可见性设置为visible
时,该按钮出现在片段的底部。 While the RL is still not visible, there are 2 buttons and when I set it to visible, the RL is covering the buttons. 当RL仍然不可见时,有2个按钮,当我将其设置为可见时,RL覆盖了按钮。
What I want to do is simply move the buttons up above that bar which becomes visible. 我想做的就是简单地将按钮移到该条上方即可看到的那条。 What I tried to do it: 我试图做到的:
rl.setVisibility(View.VISIBLE);
rl.post(new Runnable()
{
int dpToPx(final int dp)
{
return (int) (dp * getResources().getSystem().getDisplayMetrics().density + 0.5f);
}
@Override
public void run() {
int h = rl.getHeight(); //height is ready
h = dpToPx(h);
ImageButton button = (ImageButton)inflate.findViewById(R.id.button1);
float y = button.getY();
button.setY((float)h+y - 1100);
ImageButton button2 = (ImageButton)inflate.findViewById(R.id.button2);
y = button2.getY();
button2.setY((float)h+y);
}
});
The button with the -1100 (That number was just something I checked to see how it affects the position of the button and will not stay there obviously) is showing where I want it to be. 带有-1100的按钮(该数字只是我检查过的内容,以查看它如何影响按钮的位置,并且不会明显地停留在该位置)正在显示我想要的位置。 The other button is so high or low which is no longer visible. 另一个按钮太高或太低,不再可见。
How do I set the position such that the button's Y position will be the old position + the height of the newly shown relative layout so the buttons will show just above it? 如何设置位置,使按钮的Y位置成为旧位置+新显示的相对布局的高度,使按钮显示在其上方?
This is straightforward, all we need to do is to position the buttons at the y coordinate of our RelativeLayout. 这很简单,我们要做的就是将按钮定位在RelativeLayout的y坐标上。
We can get the y coordinate by calling: 我们可以通过调用以下方法获得y坐标:
rl.getY();
And since we want the button to be above the rl, we will subtract its height from the y coordinate of rl, something like this: 并且由于我们希望按钮位于rl上方,因此我们将从rl的y坐标中减去其高度,如下所示:
button.setY(rl.getY() - button.getHeight());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.