milad.moafi milad.moafi - 5 months ago 9
Android Question

How get Button coordinate?

I have a layout

activity_main.xml
:


<Button
android:id="@+id/button"
android:layout_marginTop="50dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|top"
android:text="@string/hover"/>

</FrameLayout>


How can i get Button's coordinate (x, y) on screen. for now I use:

button.getX()
button.getY()


but it
return 0.0
, How can i achieve this.

Thanks

Answer

This happens because you are getting the coordinates of your view before it's actually shown.

You can use the View.post() method, which executes some code after your View is properly initalized.

mButton.post(
    new Runnable(){
        @Override
        public void run(){
            x = mButton.getX();
            y = mButton.getY();
        }
    }
);
Comments