I have listview with arrayadapter. I want when clicking a button inside list item a specific view in that item (and not in other items) be visibile or invisible.
Heres the code what I'm doing in adapters getView() method:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = vi.inflate(layoutResourceId, null, false);
holder = new Holder();
holder.setShare((ImageView) convertView.findViewById(R.id.share));
holder.setShareButtons((LinearLayout)convertView.findViewById(R.id.shareButtons));
convertView.setTag(holder);
}
holder = (Holder) convertView.getTag();
holder.getShare().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(holder.getShareButtons().getVisibility()==View.GONE){
holder.getShareButtons().setVisibility(View.VISIBLE);
}
else{
holder.getShareButtons().setVisibility(View.GONE);
}
}
});
return convertView;
}
But all I'm getting is strange behavior. The onClickListener and setVisibilty methods are called correctly but my view sometimes get visible and sometimes not, and this depend on list scroll positon .
What I'm doing wrong and how should I solve this ?
WHen a list view is scrolled, the child views are reused and reassigned to new positions. This is for efficiency, as creating new views is expensive. However, it puts the burden on the programmer- on every getView call you must completely reset every value of the view. So if pressing a button in the child changes the visibility of one of its members, you need to remember what the visibility should be for each numeric position, and in getView you must set the appropriate visibility for every element.
The holder is meant to keep references to the inner views for performance reasons. It is not related to the data that gets presented in your list - only to the "cells" in your list. You should determine whether stuff is visible or not based on your data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With