android – Horizo​​ntalScrollView获取Visible Children

前端之家收集整理的这篇文章主要介绍了android – Horizo​​ntalScrollView获取Visible Children前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在水平滚动视图中添加了线性布局,并在布局中添加了一些文本视图.是否有可能在此布局中获得可见的孩子.

这段代码得到了所有孩子,但我想看到(仅显示)孩子:@H_502_3@

final HorizontalScrollView scroll = (HorizontalScrollView)findViewById(R.id.horizontalScrollView1);
    LinearLayout linearLayout = ((LinearLayout)scroll.findViewById(R.id.linearLayout1));
    int chilrenNum = linearLayout.getChildCount();

解决方法

好吧,经过一些搜索,我发现这个答案听取滚动事件. Implement Scroll Event Listener in Android.
我们的想法是覆盖ScrollView中的onScrollChanged,并跟踪活动中scrollview的可见部分.

这样做可以通过如下代码轻松获取可见视图:@H_502_3@

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;

以上所有代码都假定固定的子视图大小.如果您使用的是可变子大小,则需要先获取其宽度并跟踪它,然后根据父视图中的索引和位置计算可见性.@H_502_3@

猜你在找的Android相关文章