如何在listview中设置单个textview的文本颜色而不是所有textview?

时间:2012-07-17 07:50:58

标签: android listview

我在自定义列表视图中获得了文本视图,我知道如何设置文本颜色,以便更改列表中的所有文本视图。但是现在,我只想要一个特定的视图来改变颜色,比如listview中有10个项目,我只想要改变第二个textview颜色,其余的保持不变。任何的想法?非常感谢所有的帮助〜

public class CheckWinNoAdapter extends ArrayAdapter<String> {
private final Context context;
private String[] values;



public CheckWinNoAdapter(Context context, String[] values) {
    // TODO Auto-generated constructor stub
    super(context, R.layout.list_draw, values);
    this.context = context;
    this.values = values;

}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View rowView = inflater.inflate(R.layout.list_draw, parent, false);
    TextView textView1 = (TextView) rowView.findViewById(R.id.chk_tv1);


    textView1.setText(values[position]);




}

}

4 个答案:

答案 0 :(得分:6)

ListView回收其观点以避免浪费内存。因此,每次调用getView时,不要给新视图充气,而是将其分配给前一个参数convertView,然后重复使用它。 convertView是你推动滚动的视图。因此,如果TextView推迟滚动与文本视图相同,可能会发生不同的颜色,您将在文本视图中看到“yourcolor”,其中exexct defaultcolor。所以这里需要每次设置getView都称为文本颜色。

 @Override 
 public View getView(int position, View convertView, ViewGroup parent) {


    if (converView == null) {
          LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
          converView  = inflater.inflate(R.layout.list_draw, parent, false);
    }

    TextView textView1 = (TextView) converView.findViewById(R.id.chk_tv1);

    int color = (position == YOUR_POSITION) ? yourcolor : defaultcolor;
    textView1.setTextColor(color);

    textView1.setText(values[position]);

}

答案 1 :(得分:4)

您可以将getView更改为此。

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View rowView = inflater.inflate(R.layout.list_draw, parent, false);
    TextView textView1 = (TextView) rowView.findViewById(R.id.chk_tv1);

    if(position== 2){
        textView1.setColor(Color.White);//or whatever you like
    }
    textView1.setText(values[position]);




}

}

答案 2 :(得分:3)

在获取视图中这样做:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

View rowView = inflater.inflate(R.layout.list_draw, parent, false);
TextView textView1 = (TextView) rowView.findViewById(R.id.chk_tv1);


textView1.setText(values[position]);

if(Your Condition Goes Here){
textView.setTextColor(Color.RED); // Did you tried this???
}

}

答案 3 :(得分:1)

而不是传递位置传递listview的整数值,你试图将文本的颜色设置为:

if (position == INT_VALUE)//where INT_VALUE=the position at which u want to setcolor of yours
   textView.setTextColor(color);//which color u want to set 
else
  textView.setTextColor(defaultcolor);//to remaining texts