将特定的ListView项滚动到视图中
在我的应用程序中,我有一个ListView
.列表中每个项目的数据都是SomeItem
类的实例.该列表具有一个自定义ArrayAdapter
,该自定义ArrayAdapter
具有一个自定义视图以显示每个项目的各个字段并覆盖getView()
方法.用于初始化列表视图的骨架代码:
In my application, I have a ListView
. The data for each item in the list is an instance of the SomeItem
class. The list has a custom ArrayAdapter
which has a custom view to display various fields of each items and overrides the getView()
method. Skeleton code for the initialization of the list view:
ListView listView = (ListView) foo.getViewById(R.id.listView);
ArrayAdapter<SomeItem> adapter = new ArrayAdapter<SomeItem>(activity, R.layout.listItemView, R.id.textView) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Code to build the view with multiple child views
}
}
现在假设我有一个SomeItem
实例.它的关联视图可能在屏幕上显示的ListView
部分中,也可能不在该部分中.如果不是,如何获取ListView
将该特定项目滚动到视图中?
Now assume I have a SomeItem
instance. Its associated view may or may not be in the portion of the ListView
which is shown on screen. If it is not, how can I get the ListView
to scroll this particular item into view?
我发现的唯一相关的方法是ListView#requestChildRectangleOnScreen()
,它要求我提供我没有的子视图.我有用于适配器的物品.因此,我仍然不确定如何将其组合在一起.有指针吗?
The only somewhat related method I’ve found is ListView#requestChildRectangleOnScreen()
, which requires me to provide a child view which I don’t have. I have the item for the adapter. So I’m still not sure how to piece this together. Any pointers?
您可以尝试以下操作:
-
计算要显示的
SomeItem
项目的位置.您可以通过遍历传递给适配器的SomeItem
列表来完成此操作.
Calculate the position of the
SomeItem
item you want to make visible. You can do this by iterating over the list ofSomeItem
s that you pass to the adapter.
使用listView.getFirstVisiblePosition()
,listView.getLastVisiblePosition()
和计算出的位置来检查该项目在列表中是否可见.
Use listView.getFirstVisiblePosition()
, listView.getLastVisiblePosition()
and the calculated position to check if the item is visible on the list.
如果该项目不可见,请调用listView.smoothScrollToPosition(calculatedPosition)
使listView
滚动至该项目.
If the item is not visible, make listView
scroll to it by calling listView.smoothScrollToPosition(calculatedPosition)
.