Some items are null in listview onScroll method

假如想象 提交于 2019-12-07 12:30:27

问题


I have a listview and I override the onScroll event for it so that I can get the first character of the text on the first visible item of the listview. My code is as follows:

@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
    //
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
           int visibleItemCount, int totalItemCount) {
    ListView caller = (ListView) view;
    View v = caller.getChildAt(firstVisibleItem);
    if(v instanceof TextView){
        TextView tv = (TextView) v;
        if(tv != null){
            String sInitial = tv.getText().toString(); 
            sInitial = Character.toString(sInitial.charAt(0));

            TextView tvPager = (TextView) findViewById(R.id.tvPager);
            tvPager.setText(sInitial);
        }
    }
}

When the FirstVisibleItem variable is from 0 to 12(to be precise), my View v is not null and I can get the text of it. But when it goes beyond 12, my v is already null. My items are way more than 12 so it shouldn't be null.

Is there something wrong with my code? Or are there better way doing what I want? Thanks in advance!


回答1:


An android listview recycles "items" in the list when they are not visible on the screen. So anything that is not visible will be null.

http://commonsware.com/Android/excerpt.pdf



来源:https://stackoverflow.com/questions/4156217/some-items-are-null-in-listview-onscroll-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!