获取所有ListView项目(行)

时间:2014-09-13 09:22:41

标签: android android-listview

如何让ListView项目的所有孩子都得到? 有一些方法可以让孩子到位,但我无法找到任何方法来返回ListView项中所有孩子的集合。

更新:我发现我需要ListView个项目(行)。我怎么能做到这一点?
我正在做的是,将选定的ListView项目与所有项目进行比较。

4 个答案:

答案 0 :(得分:5)

您可以通过迭代从列表适配器获取所有列表项,如下所示

for (int i=0;i<adapter.getCount();i++){
     adapter.getItem(i);
}

更新:您可以使用索引将特定项目与列表适配器的所有项目进行比较,如下所示:

for (int i=0;i<adapter.getCount();i++){
    if(adapter.get(selectedIndex)==adapter.getItem(i)){
       // TODO : write code here item match 
       break; // after match is good practice to break loop instead compare rest of item even match
    }
}

答案 1 :(得分:4)

使用此方法获取列表视图的所有见解和视图:

for ( int i = 0 ; i < listView.getCount() ; i++){
    View v = getViewByPosition(i,listView);
}

public View getViewByPosition(int position, ListView listView) {
    final int firstListItemPosition = listView.getFirstVisiblePosition();
    final int lastListItemPosition =firstListItemPosition + listView.getChildCount() - 1;

    if (position < firstListItemPosition || position > lastListItemPosition ) {
        return listView.getAdapter().getView(position, listView.getChildAt(position), listView);
    } else {
        final int childIndex = position - firstListItemPosition;
        return listView.getChildAt(childIndex);
    }
}

答案 2 :(得分:2)

我猜如果ListView中的商品属于ViewGroup类型,您可以执行以下操作

ArrayList<View> children = new ArrayList<View>();
for (int i = item.getChildCount() - 1 ; i>=0; i--) {
    children.add(item.getChildAt(i));
}

答案 3 :(得分:1)

可能你正在寻找这样的东西。您需要有权访问 rootView ,您可以从中获取子视图。 onItemSelected 仅用于提供点击位置的根视图。

public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
ImageView imgView = view.findViewById(R.id.myImageView);//your imageview that is inflated inside getView() of adapter
//similarly for other views 
}