Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HorizontalScrollView get Visible Children

I added a linear layout in horizontal scroll view and in layout add some text views. Is it possible to get visible children in this layout.

This code get all child but i want to get visible (currently displaying) children only:

final HorizontalScrollView scroll = (HorizontalScrollView)findViewById(R.id.horizontalScrollView1);
    LinearLayout linearLayout = ((LinearLayout)scroll.findViewById(R.id.linearLayout1));
    int chilrenNum = linearLayout.getChildCount();
like image 528
user2106897 Avatar asked Oct 21 '22 13:10

user2106897


1 Answers

Well , after a bit of searching on SO I found this answer to listen to scroll events. Implement Scroll Event Listener in Android. The idea is to override onScrollChanged in your ScrollView and keep track of the visible part of your scrollview in your activity.

Doing that you can easily get the visible views by a code that looks like this:

int currentPosition = lastXPosition; // lastXPosition gets updated from scroll event
int layoutWidth = linearLayout.getWidth();
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int childWidth = layoutWidth/linearLayout.getChildCount();
int firstVisibleXPos = currentPosition - width/2; // currentPosition will be in the middle of the screen
int lastVisibleXPos = currentPosition + width/2;

int indexOfFirstVisible = firstVisibleXPos/childWidth;
int indexOfLastVisible  = lastVisibleXPos/ childWidth;

All the above code assumes fixed child view sizes . if you are using variable child size you will need to get their width first and keep track of it then calculate the visiblity based on index and position in parent view.

like image 151
Mr.Me Avatar answered Oct 31 '22 15:10

Mr.Me