Android Listview: getView being called multiple times on unobservable views

最后都变了- 提交于 2019-12-11 08:43:55

问题


(I have already seen this similar question) I have a ListView for which I've written a custom adapter, and an onitemclicklistener. I'm having an issue where, when any element of the list is selected, getView is called (twice) for each of the top 4 elements of the ListView, even if those elements are not visible. This happens even if I don't call notifyDataSetChanged on the adapter - those first 4 views are fetched twice regardless. Is this normal behavior? My issue is not as much that it's being called twice for them, but that it is being called at all when updating them is not needed.

By the way, I am not using wrap_content for the height or width of the listview - the height is match_parent and the width is a fixed number of dp.

The onItemClick() method of the OnItemClickListener is here:

public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

      mPicture = pictures[position];
      mPicturesAdapter.setCurrentPicture(mPicture);
      mPicturesAdapter.notifyDataSetChanged();
}

getView() from my custom Adapter (which extends BaseAdapter) is here:

public View getView(int position, View convertView, ViewGroup parent) {


    Log.v("tag", "Getting view for position "+position);

    LayoutInflater inflater = LayoutInflater.from(mContext);
    LinearLayout layout = (LinearLayout)
            inflater.inflate(R.layout.picture_thumbnail, parent, false);

// set up the linearlayout here ...

    return layout;
} 

On any item click, getView() is called for positions 0 - 3 twice regardless of which item was clicked.


回答1:


Just by modifying the adapter via

mPicturesAdapter.setCurrentPicture(mPicture);

the ListView already tries to update itself. I'm guessing the onClick method will still do it's job without you calling notifyDataSetChanged




回答2:


Actually whatever List/Group you are using to populate the ListView, you need to first empty it and then recall it. For example, if you use ListA to populate the ListView, in the second or any consecutive update you need to empty the ListA first and then add items and then populate using it.




回答3:


if (convertView != null){

           Then populate list

   }


来源:https://stackoverflow.com/questions/11463387/android-listview-getview-being-called-multiple-times-on-unobservable-views

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