我想使用以下代码为ListView中的Item着色:
holder.txtPosition = (TextView)row.findViewById(R.id.txtPosition);
holder.txtPosition.setTextColor(0xFF00CC00);
。
它工作得很好但是它也为每十个项目着色。例如:我为第一个项目设置颜色,因此每个第十个项目也会获得颜色。
如果我向下滚动并再次向上滚动,则会有更多颜色变亮。
在此图片中,我只对第一个“用户投票”文字进行着色,然后非常快速向下滚动并滚动回顶部。
这是什么样的巫术?
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class List extends ArrayAdapter<ListItem>{
Context context;
int layoutResourceId;
ListItem data[] = null;
public List(Context context, int layoutResourceId, ListItem[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
WeatherHolder holder = null;
ListItem entry = data[position];
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new WeatherHolder();
holder.txtVideos = (TextView)row.findViewById(R.id.txtVideos);
holder.txtPosition = (TextView)row.findViewById(R.id.txtPosition);
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
holder.txtcomments = (TextView)row.findViewById(R.id.txtcomment);
row.setTag(holder);
if (entry.fav){
//row.setBackgroundColor(0xFFfcf6bb);
}
}
else
{
holder = (WeatherHolder)row.getTag();
}
holder.txtTitle.setText(entry.teilnehmer);
holder.txtPosition.setText(entry.position);
int num = Integer.parseInt(entry.videos);
if (num == 0 || num > 1){
holder.txtVideos.setText(entry.videos + " Videos");
} else {
holder.txtVideos.setText(entry.videos + " Video");
}
if (holder.txtPosition.getText().equals("Ausgeschieden")){
holder.txtPosition.setTextColor(0xFFFF0000);
} else if(holder.txtPosition.getText().equals("User-Voting")){
holder.txtPosition.setTextColor(0xFF00CC00);
}
num = Integer.parseInt(entry.comment);
if (num == 0 || num > 1){
holder.txtcomments.setText(entry.comment + " Kommentare");
} else {
holder.txtcomments.setText(entry.comment + " Kommentar");
}
return row;
}
static class WeatherHolder
{
TextView txtTitle;
TextView txtVideos;
TextView txtPosition;
TextView txtcomments;
}
}
答案 0 :(得分:2)
您正在回收ListView元素(这是一件好事)。但是当这样的视图传递给你的getView
方法时,它仍处于它所持有的最后一个元素的状态;因此,如果指定setColor
,则此值也将应用于将注入容器的下一个文本。因此,在重新填充循环视图时,还应重置颜色定义:
if (holder.txtPosition.getText().equals("Ausgeschieden")) {
holder.txtPosition.setTextColor(0xFFFF0000);
} else if (holder.txtPosition.getText().equals("User-Voting")) {
holder.txtPosition.setTextColor(0xFF00CC00);
} else {
holder.txtPosition.setTextColor(R.color.your_default);
}