简体   繁体   中英

Listview item click applying to other items

I have this on my main activity:

listView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> av, View v, int position,
                    long id) {
                TextView wrapper = (TextView) v.findViewById(R.id.title);
                VideoModel o = (VideoModel) videoAdapter.getItem(position);
                wrapper.setText(o.title);
            }
        });

This code (as you would guess) changes the textview of a list view row (which is a layout). The problem is that for some reason when I click on the first row, the text changes, but it also changes on the third row (with the same text).

Any toughts?

If you want to see the whole code, refer to How to call method from activity to change layout?

Don't change Views in setOnItemClickListener instead change your data and notify adapter so that adapter will change your UI.

Example:

Model

class VideoModel {

public String title;
public String videoUrl;
public String imageUrl;
public boolean isTitleVisible;
}

Adapter

    public class VideoAdapter extends BaseAdapter{
    @Override
    public View getView(final int position, View convertView, ViewGroup parent)
    {
        VideoLayout view;
        if (convertView == null) {
            view = (VideoLayout) LayoutInflater.from(context).inflate(R.layout.video, parent, false);
        }else{
            view = (VideoLayout) convertView;
        }

        VideoModel item = (VideoModel) getItem(position);
        if (item != null) {

            view.prepare(item);
if(item.isTitleVisible){
view.changeTitle("");
}
        }

        return view;
    }
    }

On click listener:

@Override
        public void onItemClick(AdapterView<?> av, View v, int position,
                long id) {
           videoItems.get(position).isTitleVisible=! videoItems.get(position).isTitleVisible;
videoAdapter.notifyDatasetChange();
        }

This is just an example in which you change your view model and just notify adapter to change the view in onITemClick

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