简体   繁体   中英

Set Views Y position programmatically

I got a layout in which there's a RelativeLayout with a visibility of 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 . While the RL is still not visible, there are 2 buttons and when I set it to visible, the RL is covering the buttons.

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. 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?

This is straightforward, all we need to do is to position the buttons at the y coordinate of our RelativeLayout.

We can get the y coordinate by calling:

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:

button.setY(rl.getY() - button.getHeight());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM