Android ListView:获取可见项的数据索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2001760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 04:09:26  来源:igfitidea点击:

Android ListView: get data index of visible item

androidlistview

提问by Cheryl Simon

I have an Android ListViewcreated with a SimpleAdapterthat has more items in it than fit in the screen. After the list has been scrolled, I need to get the position in the data model of the first visible item in the list.

我有一个 AndroidListView创建的SimpleAdapter,其中包含的项目多于屏幕大小。滚动列表后,我需要获取列表中第一个可见项在数据模型中的位置。

Basically I want a function like: listView.getChildAt(0).getPositionInDataModel().

基本上,我要像一个函数:listView.getChildAt(0).getPositionInDataModel()

Adapterhas a few functions in it, like getItemId(position)that looked useful; however, the SimpleAdapterimplementation just returns the passed in position, not a row id like I'd hoped.

Adapter里面有一些功能getItemId(position),看起来很有用;然而,SimpleAdapter实现只返回传入的位置,而不是我希望的行 ID。

A brute force solution would be to get the View at index 0, and compare it to the view for each item in the adapter. However, there doesn't seem to be an easy way to get the view for a particular position from the adapter.

一个蛮力解决方案是在索引 0 处获取视图,并将其与适配器中每个项目的视图进行比较。但是,似乎没有一种简单的方法可以从适配器获取特定位置的视图。

Anyone have any thoughts?

有人有什么想法吗?

回答by Romain Guy

It's very easy. Just use ListView.getFirstVisiblePosition() + indexYouWant. For instance, to get the position in the adapter of the 2nd child displayed in the ListView, just use getFirstVisiblePosition() + 1.

这很容易。只需使用ListView.getFirstVisiblePosition() + indexYouWant. 例如,要获取 中显示的第二个孩子在适配器中的位置ListView,只需使用getFirstVisiblePosition() + 1.

No need for all the scary stuff shown in the reply above :)

不需要上面回复中显示的所有可怕的东西:)

回答by varma

listView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
    public void onItemSelected(AdapterView<?> parent,View view, int pos, long id) 
    {
        AisleId= parent.getSelectedItemId();
    }
    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub
    }
});

In this we will get list item Id parent.getSelectedItemId();

在此我们将获得列表项 Id parent.getSelectedItemId();

回答by Cyril Mottier

Simply use the getPositionForView(View)(see documentation). The main advantage of this method is it also works with descendant Views of an item.

只需使用getPositionForView(View)见文档)。这种方法的主要优点是它也适用于View项目的后代s。