Android更改ListView项文字颜色

7

我试图在基于标志的列表视图中更改一些项目的文本颜色(或背景颜色)。经过长时间的搜索,我没有找到如何做到这一点。我会在特定操作后调用下面的循环来更改颜色:

ListView _listView = (ListView) findViewById(R.id.listView2);

        for (int i=0;i<=_listView.getCount();i++)
        {   
           if(Falg == True)
           {
            //here i want to change the list view item color or backgroud color
           }
        }

你好,获取相应的列表视图元素,例如:View element = _listView.getAdapter().getItem(position),并设置颜色元素.setBackgroundColor(Color.rgb(202, 202, 202)); - Remarkable
如果您想自定义布局,我建议使用自定义适配器。 - Rakeeb Rajbhandari
4个回答

27

您可以覆盖ArrayAdapter的getView方法并更改颜色:

ArrayAdapter<String> adapter = 
                    new ArrayAdapter<String>(getApplicationContext(), 
                    android.R.layout.simple_list_item_1, 
                    myList) {

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

        View view = super.getView(position, convertView, parent);
        TextView text = (TextView) view.findViewById(android.R.id.text1);

        if (flag == True) {
            text.setTextColor(Color.BLACK);
        }   

        return view;
    }
};

1
ViewGroup和flag是从哪里来的?@AdnanMulla - gumuruh
flag是您维护的全局变量,viewgroup在getView方法中传递。 - Adnan Mulla
重写了getView()方法后,OnItemClick没有被调用。我的ListView只有一个TextView。 - user3491799
这是一些非常好的技巧和知识.. @AdnanMulla 做得很好。 - Zuko

4
你可以直接在自定义的Adapter中完成这个操作。
请参考Adapter.getView()
你可以在这个方法中填充行布局,并动态地改变视图的颜色和其他内容。

3
创建自定义布局,在该布局中定义您的颜色。
就像这样:
<? xml version="1.0" encoding=" utf-8 "? >
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/tv"
 android:textColor="@color/white"  // Here You define your desired color
 android:layout_width="fill_parent"
 android:gravity="center"
 android:layout_height="fill_parent"/>

在适配器中使用此布局,如下所示:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(
    this, R.layout.custom_textview, info);
lv.setAdapter(adapter); 

这样,您就不需要使用自定义适配器。

-3

你可以设置字体颜色样式... 类似于

textView.setText(Html.fromHtml("<b><u>"+string+"<b><u>"));

当你将文本填充到你的列表视图中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接