在我的Android应用程序中,我有一个带有自定义适配器的列表视图,它有两个textview。第一个textview将始终以文本形式显示,但在某些情况下,第二个textview将为空。我只在有文本的地方为第二个textview提供背景颜色。我在这里面临的问题是,一旦我滚动列表视图,颜色就会分配给整个列表视图。
数据以下列方式传递给适配器:
String time_array[] = new String[]{"12 AM","1 AM","2 AM","3 AM","4 AM","5 AM","6 AM","7 AM","8 AM","9 AM","10 AM","11 AM","12 PM","1 PM","2 PM","3 PM","4 PM","5 PM","6 PM","7 PM","8 PM","9 PM","10 PM","11 PM"};
String item_array[] = new String[]{"item1","item1","item1","","","","item1","item1","item1","","","","item1","item1","item1","item1","","","","","item1","item1","item1",""};
for(int i=0;i<time_array.length;i++)
{
HashMap<String, String> map = new HashMap<String, String>();
map.put("Time", time_array[i]);
map.put("Item", item_array[i]);
appointment_aaray.add(map);
}
下面是我用于listview并着色第二个textview的代码:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if(convertView==null)
{
viewHolder=new ViewHolder();//
convertView = inflater.inflate(R.layout.appointment_timings_row, null);
viewHolder.txt_time = (TextView)convertView.findViewById(R.id.txt_time);
viewHolder.txt_item = (TextView)convertView.findViewById(R.id.txt_item);
convertView.setTag(viewHolder);
}
else
{
viewHolder = (ViewHolder) convertView.getTag();
}
HashMap<String, String> map = new HashMap<String, String>();
map = data.get(position);
viewHolder.txt_time.setText(map.get("Time"));
viewHolder.txt_item.setText(map.get("Item"));
if (position % 2 == 1) {
convertView.setBackgroundColor(Color.parseColor("#FFFFFF"));
} else {
convertView.setBackgroundColor(Color.parseColor("#FEF8F8"));
}
if(map.get("Item").equals(""))
{
}
else
{
viewHolder.txt_item.setBackgroundColor(activity.getResources().getColor(R.color.item_text_color));
}
return convertView;
}
有人可以帮我解决我在这里失踪的问题吗? 谢谢Adavance!
答案 0 :(得分:2)
列表视图将为第一个可见行创建行,之后将重复使用相同的行。因此,在if
条件中设置默认颜色
if(map.get("Item").equals(""))
{
viewHolder.txt_item.setBackgroundColor(default_color);
}
else
{
viewHolder.txt_item.setBackgroundColor(activity.getResources().getColor(R.color.item_text_color));
}