HorizontalScrollView Gets Visible Kids

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

This code gets all the children, but I want to get only visible (currently) only children:

final HorizontalScrollView scroll = (HorizontalScrollView)findViewById(R.id.horizontalScrollView1);
    LinearLayout linearLayout = ((LinearLayout)scroll.findViewById(R.id.linearLayout1));
    int chilrenNum = linearLayout.getChildCount();
+5
source share
1 answer

Well, after a little search in SO, I found this answer to listen to scroll events. Implement a scroll event listener in Android . The idea is to override onScrollChangedin yours ScrollViewand keep track of the visible portion of your scrollview in your activity.

, , :

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;

. , , .

+3

All Articles