【问题标题】:How do I change the list item's background after smooth scrolling to it?平滑滚动到列表项后如何更改列表项的背景?
【发布时间】:2013-10-11 16:06:29
【问题描述】:

当列表项不在屏幕上时,我在获取列表项的视图时遇到问题。

首先我平滑滚动到它

//locationsList is a listview
locationsList.post(new Runnable() {
    @Override
    public void run() {
        locationsList.smoothScrollToPosition(k);
    }
});

那我想做

View listItem = locationsList.getChildAt(k);
listItem.setBackgroundColor(getResources().getColor(R.color.highlight));

滚动完成后如何调用它?

【问题讨论】:

  • 所以基本上你想知道滚动完成的时间?
  • getview 将在该位置可见时被调用,因此请尝试在 getview 中更改背景。
  • @Lefteris 是的,如果视图不在屏幕上,getChildAt 将返回 null
  • getView 听起来不错,我试试看。

标签: android android-listview smooth-scrolling


【解决方案1】:

为列表项视图设置一个唯一标签。每当您想更改滚动时,使用此标签访问此列表项。

【讨论】:

    【解决方案2】:

    如果您只想知道滚动完成的时间,则需要在列表视图中添加onScrollListener

    locationsList.setOnScrollListener(new OnScrollListener() {
    
                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {
                    if(scrollState==OnScrollListener.SCROLL_STATE_IDLE){
                        View listItem = locationsList.getChildAt(k);
                        listItem.setBackgroundColor(getResources().getColor(R.color.highlight));
                    }
    
                }
    
                @Override
                public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                }
            });
    

    当然,上面需要一个逻辑来更新背景只有在你之前启动滚动时,所以你应该使用一个布尔标志并在locationsList.smoothScrollToPosition(k);执行时将其设置为true,那么如果这个标志为true,在 scrollListener 中运行代码并将标志设置回 false

    【讨论】:

    • 不知道为什么,但是它将 scrollState 设置为 OnScrollListener.SCROLL_STATE_IDLE 太快了,并且该项目还没有出现在屏幕上
    • 你确定它首先开始滚动,意味着它通过你的runnable然后调用scrollStateChanged事件?
    • 是的,在我的可运行文件被调用后它滚动了一点。我也设置了断点来观察滚动状态的变化。
    • 奇怪,这是official documentation
    • getview 方法也有效,但它对我来说似乎很恶心,但它有效,所以我想我会走那条路,因为这很时髦。 (尽管我认为这个看起来是正确的答案)
    猜你喜欢
    • 1970-01-01
    • 2010-10-13
    • 1970-01-01
    • 1970-01-01
    • 2013-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多