Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android ScrollView: Automatically scroll to a few pixels (dips) above a certain view

I am aware that I should decide how many pixels based on density.. not hard coded.

I have section headers and items displayed in a scrollview and I want to scroll to a certain section header (the one for the current date) while making it clear that it is not the top of the screen (show about half of the previous item).

How can I do that? I do not want this automatic scroll to be animated.

like image 962
700 Software Avatar asked Mar 09 '26 21:03

700 Software


1 Answers

With View.requestRectangleOnScreen() you can scroll to show a particular rectangle (the linked method allows disabling animation). You still will have to calculate that rectangle, but once you have the position of the particular child (your header) you can easily do that getting the size of the ScrollView. You could consider the small offset you want in calculating that rectangle or just do a scrollBy() after requestRec....() (the former way is better I think).

An easy way to use a density independent dimension is to define it in xml as a dimension resource.

-- edit: you get the position of the child in parent with getLeft() / getTop().

like image 118
bigstones Avatar answered Mar 12 '26 07:03

bigstones



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!