在列表视图中设置文本的颜色

时间:2014-03-11 19:23:54

标签: android listview android-listview

我有一个简单的列表视图,其值在两个字符串数组中定义,如果它等于某个值,我希望列表视图中的文本颜色会发生变化。

以下是我尝试过的,无效的

///rest of oncreate above
var = new String[]{"Text", "Words", "Other"};
val = new String[]{"t", "w", "o"};
preparelist();
///rest of oncreate would go here...
}

private void preparelist(){
thelist = new ArrayList<HashMap<String, String>>();

        for (int i = 0; i < var.length; i++) {
            map2 = new HashMap<String, String>();

            map2.put("one", var[i]);
            map2.put("two", val[i]);
            thelist.add(map2);
        }


        try {
            adapter = new SimpleAdapter(this, thelist, R.layout.row,
                    new String[] {"one", "two" }, new int[] {
                             R.id.one, R.id.two });

            list.setAdapter(adapter);
            setListViewHeightBasedOnChildren(list);
        } catch (Exception e) {

        }
TextView t = (TextView)findViewById(R.id.one);
if(t.equals("Words")){
t.setTextColor(Color.BLUE);
}
}

基本上在这个例子中,我希望列表中等于“Words”的所有内容都变为蓝色,因为if语句会检查,但它不起作用

4 个答案:

答案 0 :(得分:2)

您需要通过扩展SimpleAdapter类并重新实现getView()方法来定义自定义适配器类。在getView()内,为文本颜色添加条件。

扩展SimpleAdapter的一个很好的例子是here

答案 1 :(得分:2)

您应该使用BaseaAdapter,然后在getView中定义您想要的内容

public class Adapter extends BaseAdapter{

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return *YOUR ARRAY SIZE OR LENGHT*;
    }

    @Override
    public Object getItem(int arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public long getItemId(int arg0) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int arg0, View arg1, ViewGroup arg2) {
        View inflate = View.inflate(CONTEXT, COM.EXAMPLE.R.layout.list, null); //Your XML layout, you can even create it programmatically
        TextView tv = (TextView)inflate.findViewById(COM.EXAMPLE.R.id.textView1);
        tv.setText(YOURARRAY[arg0]);
        tv.setTextColor(Color.BLUE);

        return inflate;
    }

}

答案 2 :(得分:1)

listviews应该与Adapters一起使用,并且您希望覆盖适配器的getView()方法。

你应该看看这个链接,我找到了一个关于listviews如何工作的精彩教程: vogella-tutorial

以下是可行的代码示例:

listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,new String[]{"Text", "Words", "Other"}) {
@Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
    TextView resultTextView = (TextView)super.getView(position, convertView, parent);
    resultTextView.setText(textToDisplay);

    if ("Words".equals(textToDisplay)){
        resultTextView.setTextColor(Color.BLUE);
    }else{
        resultTextView.setTextColor(Color.BLACK);
    }

    return resultTextView;
}});

请注意,此代码适用于回收视图,但是如果要在getView方法中创建自己的TextView,则应该回收它,否则列表视图将遇到不良性能(请查看教程)。

答案 3 :(得分:-3)

我相信你需要稍微改变你的if语句:

String tString = t.getText().toString());

if(tString == "Words"){
   t.setTextColor(Color.BLUE);
}
相关问题