How to get absolute coordinates from Views in a RelativeLayout

自古美人都是妖i 提交于 2021-01-28 01:22:22

问题


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.


回答1:


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));
            }
        });


来源:https://stackoverflow.com/questions/32738348/how-to-get-absolute-coordinates-from-views-in-a-relativelayout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!