android - Horizo​​ntalScrollView 获取可见子项

标签 android android-layout

我在水平 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 - Horizo​​ntalScrollView 获取可见子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15655274/

相关文章:

Android searchview隐藏键盘但不失去焦点

android - 在 Android 中,我可以在布局 xml 中使用 Assets 中的图像吗?

android - 在 ConstraintLayout 中缩放矢量图形

ICS 文本中的 android:ellipsize 在省略号之后继续

android - android playstore 是否支持非续订订阅?

android - 用户属性不可用于通知

android - 如何图像按钮在 android 的 ListView 中创建圆圈?

android - 如何使用 MonkeyRunner 将 Extra 传递给 Android Intent ?

android - 找不到 Xamarin.Auth.AccountStore.Create

android - 将字符串值从自定义对话框传递到另一个 Activity