在我的具体问题中,我有一个列表视图。在这个列表视图中,我希望列表的第一行始终具有绿色的背景颜色。我使用以下代码实现了这一点:
listView.setSelection(3);
View element = listView.getChildAt(0);
element.setBackgroundColor(Color.GREEN);
在背景中我使用自定义适配器来填充列表视图,因为行被回收,绿色在出现的新行上是多余的。以下是我的getView方法代码:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View first = listView.getChildAt(0);
if (convertView == null){
convertView = inflater.inflate(R.layout.list, parent, false);
}
TextView textView = ((TextView) convertView.findViewById(R.id.textView2));
textView.setText(lyrics[position]);
if(){ // Need to reference the first row here.
textView.setBackgroundColor(Color.GREEN);
}else {
textView.setBackgroundColor(Color.WHITE);
}
return convertView;
}
}
所以在我的情况下,我需要知道列表视图中的第一个可见位置,以便我可以撤消重复的背景着色。有什么办法可以实现这个目标吗?只要可行,我愿意改变逻辑。
答案 0 :(得分:2)
ListView的视图已被回收,因此您应该使用适配器getView
方法 - 可能就在return convertView
之前:
if(position == 0) {
convertView.setBackgroundColor(Color.GREEN);
} else {
convertView.setBackgroundColor(Color.WHITE); // or whatever color
}
return convertView;
不需要以下代码:
View element = listView.getChildAt(0);
element.setBackgroundColor(Color.GREEN);
答案 1 :(得分:1)
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View first = listView.getChildAt(0);
if (convertView == null){
convertView = inflater.inflate(R.layout.list, parent, false);
}
TextView textView = ((TextView) convertView.findViewById(R.id.textView2));
textView.setText(lyrics[position]);
if(position==getFirstVisiblePosition()){ // Need to reference the first row here.
textView.setBackgroundColor(Color.GREEN);
}else {
textView.setBackgroundColor(Color.WHITE);
}
return convertView;
}
}