Android listview imageview in listitem gets hidden on scroll
I am having this weird problem when trying to dynamically set visibility and image drawable of imageview in list item. When it initially loads its shows up completely fine but when I scroll it up or down some of the images doesn't show up.
Here is the code:
@Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; Alarm o = items.get(position);
if (convertView == null)
{
convertView = View.inflate(mcontxt, R.layout.facelistitem, null);
holder = new ViewHolder();
holder.ind = (ImageView) convertView.findViewById(R.id.imgind);
holder.name = (TextView) convertView.findViewById(R.id.txtname);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder)convertView.getTag();
}
if (o != null) {
String name;
StringBuilder strb = new StringBuilder().append(
pad(o.GetAlarmHour())).append(":").append(
pad(o.GetAlarmMinute()));
if (position == 0) {
name = "Add Alarm";
} else if ((o.getAlarmName() != null)
&& !o.getAlarmName().equals("")) {
name = o.getAlarmName().trim() + " - " + strb.toString();
} else {
name = strb.toString();
}
//TextView tt = (TextView) v.findViewById(R.id.txtname);
//ImageView iv = (ImageView) v.findViewById(R.id.imgind);
if (holder.name != null) {
holder.name.setText(name);
}
if (holder.ind != null) {
if (name.equalsIgnoreCase("Add Alarm"))
holder.ind.setVisibility(View.INVISIBLE);
if (o.IsAlarmOn())
holder.ind.setImageDrawable(mcontxt.getResources().getDrawable(
R.drawable.alarmon));
else
holder.ind.setImageDrawable(mcontxt.getResources().getDrawable(
R.drawable.alarmoff));
}
/*
* if(bt != null){ bt.setText("Status: "+ o.getOrderStatus()); }
*/
}
return convertView;
}
Is the whole ListView
turning black? You may need to set:
android:cacheColorHint="@android:color/transparent"
on your ListView
.
Otherwise, you may need to provide an alternative to your INVISIBLE
setting:
if (name.equalsIgnoreCase("Add Alarm")) {
holder.ind.setVisibility(View.INVISIBLE);
} else {
holder.ind.setVisibility(View.VISIBLE);
}
If you don't do this then recycled views will sometimes be INVISIBLE
when you don't intend them to be.
All you need to do is set your image to VISIBLE in getView before setting it INVISIBLE/GONE again (if necessary).
In my particular example:
holder.ivImageLeft.setVisibility(View.VISIBLE);
holder.ivImageRight.setVisibility(View.VISIBLE);
if (i == 0) {
holder.ivImageLeft.setVisibility(View.GONE);
} else {
holder.ivImageRight.setVisibility(View.GONE);
}
链接地址: http://www.djcxy.com/p/67338.html