Joyson
Joyson

Reputation: 1653

How to get the x,y coordinates of a view in android?

I have used the following code to get the Location (x,y) coordinates of a view in my layout.I have a button and the following code to get its location on the scren.However it force closes the app when using this code.Also note that this statement has been called after setContentView().Following is the code

Toast.makeText(MainActivity.this, button1.getTop(),Toast.LENGTH_LONG).show();

And following is the Error:

 E/AndroidRuntime(11630): android.content.res.Resources$NotFoundException: String resource ID #0x196

.How do i get the view's (say a Button in my case) location on the screen(x,y coordinates)?

Upvotes: 7

Views: 24766

Answers (3)

Braian Coronel
Braian Coronel

Reputation: 22867

Precondition: MyButton reference exists

AtomicInteger leftButton = new AtomicInteger();
myButton.getViewTreeObserver().addOnGlobalLayoutListener(
    () -> {
        if (leftButton.get() == 0) {
            leftSubtitle.set(myButton.getLeft());

            //do something once you get the value..
        }
    }
);

Upvotes: 1

WarrenFaith
WarrenFaith

Reputation: 57672

the method you use expect integer values as references of R.string.whatever. Cast the getTop() return value to String should work.

Toast.makeText(MainActivity.this, String.valueOf(button1.getTop()), Toast.LENGTH_LONG).show();

To get the x/y of the button (since API 11):

Toast.makeText(MainActivity.this, (int)button1.getX() + ":" + (int)button1.getY(), Toast.LENGTH_LONG).show();

Doc:

The visual x position of this view, in pixels.

For API below 11 you are on the right way: getTop() is the equivalent of getY() but without a possible animation/translation. getLeft() is the quivalent of getX() with the same restriction.

Upvotes: 8

Longerian
Longerian

Reputation: 723

button1.getTop() returns a int number, Toast.makeText() treat that int number as a string resource id which is not existed in fact, so it crashes.

Try to use button1.getTop() + "" to change to a string.

Upvotes: 0

Related Questions