Search code examples
javaandroidcoordinatesandroid-scrollviewandroid-relativelayout

How to get absolute coordinates from Views in a RelativeLayout


I have the following Layout:

<ScrollView>
    <RelativeLayout>
        <RelativeLayout>
            <View
                android:id="@+id/vline"
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="@color/md_white_1000"/>
            <ImageButton>...</ImageButton>
        </RelativeLayout>
    </RelativeLayout>
</ScrollView>

The different Layouts have there own content and height on different screens of course.

Now I want, by pressing the ImageButton, to smoothly scroll my ScrollView up so that the Views upper left corner is in the upper left corner of the specific screen.

I tried:

ImageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scrollView.smoothScrollTo(0, vline.getTop());
            }
        });

and all the other "getY()" methods, but no one bring the result I want to have. It just scrolls all of my content fully high.

I'm just getting started with Android so thank you for your help.


Solution

  • Here is the Solution:

    button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int statusbarHeight = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getHeight()
                            - YOURVIEW.getHeight();
                    int[] position = new int[2];
                    vline.getLocationInWindow(position);
                    scrollView.smoothScrollBy(0, (position[1]-statusbarHeight));
                }
            });