我在水平 ScrollView 中添加了一个线性布局,并在布局中添加了一些 TextView 。是否有可能在此布局中获得可见的 child 。
此代码获取所有子项,但我只想显示(当前显示)子项:
final HorizontalScrollView scroll = (HorizontalScrollView)findViewById(R.id.horizontalScrollView1);
LinearLayout linearLayout = ((LinearLayout)scroll.findViewById(R.id.linearLayout1));
int chilrenNum = linearLayout.getChildCount();
最佳答案
好吧,在对 SO 进行一些搜索之后,我找到了这个答案来监听滚动事件。 Implement Scroll Event Listener in Android .
这个想法是在您的 ScrollView
中覆盖 onScrollChanged
并在您的 Activity 中跟踪 ScrollView 的可见部分。
这样做,您可以通过如下代码轻松获得可见 View :
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;
以上所有代码都假定固定的 subview 大小。如果您使用的是可变子尺寸,则需要先获取它们的宽度并对其进行跟踪,然后根据父 View 中的索引和位置计算可见性。
关于android - HorizontalScrollView 获取可见子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15655274/