简体   繁体   中英

Strange behaviour of ImageViews of the last item in ListView

I have a ListView with a custom adapter. In every row there is an ImageView that is visible only under certain constraints. The problem is that if the first row has this ImageView visible, so it is for the last row as well and viceversa.

Here is the getView() code of my adapter.

public View getView(int position, View view, ViewGroup parent) {
    if (view == null) {
        LayoutInflater inflater = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.row_idea, null);
    }

    Idea idea = mIdeas.get(position);

    if (idea != null) {
        ImageView imgAlarm = (ImageView) view
                .findViewById(R.id.imgAlarm_rowIdea);
        if (idea.getTimeReminder() != null)
            imgAlarm.setVisibility(ImageView.VISIBLE);

        TextView lblTitle = (TextView) view
                .findViewById(R.id.lblTitle_rowIdea);
        lblTitle.setText(idea.getTitle());

        TextView lblDescription = (TextView) view
                .findViewById(R.id.lblDescription_rowIdea);
        lblDescription.setText(idea.getDescription());
    }
    return view;
}

mIdeas is an ArrayList with all the data to display in the ListView . imgAlarm is the ImageView that I told above.

You'll want to revert the visibility status of the ImageView if the condition is not met so you don't have problems with a potential recycled view(which could have the ImageView already visible and appearing when it shouldn't):

if (idea.getTimeReminder() != null) {
     imgAlarm.setVisibility(ImageView.VISIBLE);
} else {
    imgAlarm.setVisibility(ImageView.INVISIBLE); // or GONE
}

Change

if (idea.getTimeReminder() != null)
            imgAlarm.setVisibility(ImageView.VISIBLE);

to

if (idea.getTimeReminder() != null)
            imgAlarm.setVisibility(ImageView.VISIBLE);
else
            imgAlarm.setVisibility(ImageView.GONE);

What's happening here is that the adapter is "recycling" the views. So in the case you're seeing in your tests, the last view and the first view are actually the same instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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