【问题标题】:what limits the index for listview.getChildAt(index)什么限制了 listview.getChildAt(index) 的索引
【发布时间】:2013-10-02 17:44:29
【问题描述】:

当我调用listview.getChildAt(index) 时,index 应该是什么让我得到一个非空值? index 必须是 [0, listview.getChildCount() ) 范围内或 [0, adapter.getCount() ) 范围内的值。这是listview count vs adapter count in android 的后续问题

【问题讨论】:

    标签: android android-layout android-listview android-arrayadapter android-adapter


    【解决方案1】:

    您将需要使用 [0, listview.getChildCount() ) 或包裹在 try/catch 中,因为这可能会给您一个 IndexOutOfBoundsException。然而,如果你得到一个null 值,那可能是因为ListView 还没有完成绘制。您需要发布Runnable 来解决此问题。

    例如,这是我获取计数并确定List 中的项目是否比屏幕上的项目多的方式:

    listView.post(new Runnable()
    {       
        public void run()
        {
            int numItemsVisible = listView.getLastVisiblePosition() -
                                    listView.getFirstVisiblePosition();
            if (itemsAdapter.getCount() - 1 > numItemsVisible && numItemsVisible > -1)
            {   //do stuff  }                                   
            else
            {   
                //do other stuff
            }               
        }
    });
    

    【讨论】:

    • 来自适配器的 getItem 也一样吗?还是如我所料,受adapter.getCount() 的限制?顺便说一句,我会测试并报告。 +1
    • 这将取决于Adapter 计数,是的
    【解决方案2】:

    那就是[0, listview.getChildCount() )

    【讨论】:

      【解决方案3】:

      ListView 只是带有子项(行)的视图。 getChildAt 的范围是 [0, listview.getChildCount())。 ListView 只包含现在可见的视图女巫。 Adapter getCount() 返回数据行数,比如 ListView 的最大长度。

      【讨论】:

        【解决方案4】:

        根据我的实验,它是这样工作的。 ListView 是适配器的一部分。因此,如果一个适配器有 500 个项目,而 ListView 有十 (10) 个项目。 ListView 中的十个代表动态视图。因此,如果 firstVisibleItem 是适配器中的项目 217,则 ListView 的索引范围将为 (217,…,226) 而 listView.getChildCount() 仍将返回 10。

        因此答案是:

        getChildAt(x) | x : [0+firstVisibleItem, listview.getChildCount()+firstVisibleItem)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-10-16
          • 1970-01-01
          • 2021-12-17
          • 2012-08-17
          • 2010-11-02
          相关资源
          最近更新 更多