【问题标题】:Get all full visible objects on lListView获取 lListView 上的所有完整可见对象
【发布时间】:2012-11-01 15:44:29
【问题描述】:

我有一个 ListView,其中包含更多元素,然后我可以一次显示。现在我想从所有元素中获取索引,这些元素完全可见(-> 不包括仅部分可见的元素)。 此时我使用getFirstVisiblePosition() & getLastVisiblePosition()for-loop 来迭代它们,但是这些方法并不像我想要的那样准确。

有没有更好的解决方案?

【问题讨论】:

    标签: android listview


    【解决方案1】:

    ListView 将其行组织在一个自上而下的列表中,您可以使用getChildAt() 访问该列表。所以你想要的很简单。让我们获取第一个和最后一个视图,然后检查它们是否完全可见:

    // getTop() and getBottom() are relative to the ListView, 
    //   so if getTop() is negative, it is not fully visible
    int first = 0;
    if(listView.getChildAt(first).getTop() < 0)
        first++;
    
    int last = listView.getChildCount() - 1;
    if(listView.getChildAt(last).getBottom() > listView.getHeight())
        last--;
    
    // Now loop through your rows
    for( ; first <= last; first++) {
        // Do something
        View row = listView.getChildAt(first);
    }
    

    加法

    现在我想从完全可见的所有元素中获取索引

    我不确定那句话是什么意思。如果上面的代码不是您想要的索引,您可以使用:

    int first = listView.getFirstVisiblePosition();
    if(listView.getChildAt(0).getTop() < 0)
        first++;
    

    拥有一个与您的适配器相关的索引(即adapter.getItem(first)。)

    【讨论】:

    • listView.getChildAt(index).getTop() 技巧对我有用..谢谢
    【解决方案2】:

    我这样做的方法是扩展您在ListView 适配器的getView 中传递的任何视图,并覆盖方法onAttachedToWindowonDetachedToWindow 以跟踪可见的索引。

    【讨论】:

      【解决方案3】:

      试试onScrollListner,你可以使用getFirstVisiblePosition和getLastVisiblePosition。

      这个this 链接,它包含类似类型的问题。我想你在那里得到了答案..,.

      【讨论】:

      • 感谢您的链接,但这个问题正是我所遇到的,它给我的不是完全可见的 ListEntry 的索引,它返回屏幕上的所有项目...
      【解决方案4】:

      上面的代码有些正确。如果您需要找到完全可见的视图位置,请使用以下代码

      public void onScrollStateChanged(AbsListView view, int scrollState)  {
          // TODO Auto-generated method stub
          View v = null;
      
          if (scrollState == 0) {
              int first =0;
              if (view.getChildAt(first).getTop() < 0)
                  first++;
              int last = list.getChildCount() - 1;
              if (list.getChildAt(last).getBottom() > list
                      .getHeight())
                  last--;
              // Now loop through your rows
              for ( ; first <= last; first++) {
                  // Do something
      
                  View row = view.getChildAt(first);
                  // postion for your row............ 
                  int i=list.getPositionForView(row);
              }
          }
              // set the margin.
      }
      

      【讨论】:

        猜你喜欢
        • 2012-01-20
        • 1970-01-01
        • 1970-01-01
        • 2015-10-18
        • 1970-01-01
        • 2016-01-10
        • 2017-05-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多