Search code examples
javaandroidandroid-layoutandroid-viewfloating-action-button

Retrieve the X & Y of FAB


I have a RelativeLayout and inside this layout i have fab button:

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_margin="8dp"/>

Now , in java I want to now, where is the fab position on the screen.I used this method according this post : enter link description here

private Point getPointOfView(View view) {
    int[] location = new int[2];
    view.getLocationInWindow(location);
    return new Point(location[0], location[1]);
}

and using this method like this:

fab = findViewById(R.id.fab);
for (int i = 0; i < pv.length; i++) {
    pv[i] = new Point(getPointOfView(fab).x ,getPointOfView(fab).y);
}

but getPointOfView(fab).x and getPointOfView(fab).y return 0.how could i retrieve the X & Y fab button?


Solution

  • You can make use of View#post() API, then your code would be replaced with this one:

    FloatingActionButton fab = findViewById(R.id.fab);
    fab.post(new Runnable() {
        @Override
        public void run() {
            // this callback will be executed after view is laid out
            for (int i = 0; i < pv.length; ++i) {
                pv[i] = new Point(getPointOfView(fab).x ,getPointOfView(fab).y);
            }
        }
    })