简体   繁体   English

获取listview项目的可见位置

[英]Get visible position of listview item

I have a custom cursor adapter to populate a list view in my fragment. 我有一个自定义游标适配器来填充我的片段中的列表视图。

I want to set the visibility of certain elements within the list view items, depending on whether the item is the first visible one in the list or not. 我想设置列表视图项中某些元素的可见性,具体取决于该项是否是列表中的第一个可见元素。 Is it possible to get that info in the bindView() method of the Cursor adapter? 是否可以在Cursor适配器的bindView()方法中获取该信息?

Adapter's purpose plan: 适配器的目的计划:

  1. Create views 创建视图
  2. Attaching data to them 将数据附加到它们
  3. Return the view for the ListView to use. 返回要使用的ListView视图。

Conclusion: Adapter doesn't know where the view it's creating will be shown. 结论:适配器不知道它所创建的视图将在何处显示。

However, the ListView does know about this and it's probably the only way you can get this working. 但是, ListView确实知道这一点,这可能是你能够实现这一目标的唯一方法。

Example code to get you started: 入门的示例代码:

listView.setOnScrollListener(new AbsListView.OnScrollListener() {
    int previousFirst = -1;
    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        if (previousFirst != firstVisibleItem) {
            previousFirst = firstVisibleItem;
            TextView textView = (TextView) view.findViewById(R.id.title);
            if (textView != null) textView.setText("First: " + firstVisibleItem);
        }
    }
});

Problems with this code: 这段代码有问题:

  • Once the first item changes, you need to set it's text back to the previous one. 第一个项目更改后,您需要将其文本设置回上一个项目。
  • Same goes with the view hierarchy. 视图层次结构也是如此。 If you change how this view looks, after it's not the first one anymore you need to change it back. 如果您更改此视图的外观,则在不再是第一个视图后,您需要将其更改回来。
  • ListView doesn't scroll upon creation. ListView不会在创建时滚动。 So the first item will not have the text changed until you scroll manually. 因此,在手动滚动之前,第一项不会更改文本。

ListView doesn't include the options to customize the first visible item internally, that's why you have to use all these dirty hacks. ListView不包含在内部自定义第一个可见项的选项,这就是您必须使用所有这些脏黑客的原因。 However, it is possible :). 但是,有可能:)。 I leave you to overcome these problems yourself. 我让你自己克服这些问题。

Good luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM