Colors 彩色列表视图

Colors 彩色列表视图,colors,android-listview,Colors,Android Listview,是否可以为(动态)ListView中的不同行设置不同的颜色 我知道我可以设置背景颜色,例如在项目单击事件侦听器上,但我想知道在向适配器添加项目时是否有一种方法可以动态设置颜色 还好吧? itemAdapter=newArrayAdapter(这个,android.R.layout.simple\u list\u item\u 1,itemArray){ @凌驾 公共视图getView(int位置、视图转换视图、视图组父视图){ 查看行; LayoutFlater充气器=(LayoutFlater

是否可以为(动态)ListView中的不同行设置不同的颜色

我知道我可以设置背景颜色,例如在项目单击事件侦听器上,但我想知道在向适配器添加项目时是否有一种方法可以动态设置颜色

还好吧?
itemAdapter=newArrayAdapter(这个,android.R.layout.simple\u list\u item\u 1,itemArray){
@凌驾
公共视图getView(int位置、视图转换视图、视图组父视图){
查看行;
LayoutFlater充气器=(LayoutFlater)getSystemService
(上下文、布局、充气机和服务);
if(null==convertView){
行=充气机。充气(android.R.layout.simple\u list\u item\u 1,空);
}否则{
行=转换视图;
}
行.setBackgroundColor(getItem(位置).getInt(“颜色”);
TextView tv=(TextView)row.findViewById(android.R.id.text1);
tv.setText(getItem(position).getString(“text”);
返回行;
}
};

您必须编写自己的自定义ListAdapter。如果数据是数组或ArrayList,只需扩展ArrayAdapter,并重写
getView()
方法。关于编写
getView()
实现,有很多答案,但对于您的特定问题,基本答案是您需要添加一些逻辑:

public View getView(int pos, View convertView, ViewGroup parent) {

    //do initialization work with the convertView

    if(/*some logic determining whether the view should be colored*/) {
        convertView.setBackgroundColor(myColor);
    } else convertView.setBackgroundColor(defaultColor);
}

要记住的重要一点是,如果不符合逻辑标准,请将其设置回其他颜色,因为视图会被回收和重用,否则可能会处于意外状态。

仅对此进行扩展,因为在聊天中提到这是为了区分发送和接收的消息。您还应该覆盖适配器的
add()
。将其设置为可以传入一个标志,然后将该标志附加到某种内部
列表
到适配器。然后,在
getView()
方法中,您可以执行逻辑检查
if(list.get(pos)=MESSAGESENT)backgroundColor1 else backgroundColor2
。轻微更正:无需重写
add()
。您只需使用
getItem(pos)
即可。好的。因此,我应该使用ArrayAdapter或ArrayAdapter来保存其他数据,而不是ArrayAdapter?顺便说一句,在我看到你的两条信息之前,我写了这封信,@Atlos。但拥有ArrayAdapter还不够吗?这取决于itemArray对象是什么,以及getInt(“颜色”)的功能,但如果它正常工作,我会说它没问题。:)
public View getView(int pos, View convertView, ViewGroup parent) {

    //do initialization work with the convertView

    if(/*some logic determining whether the view should be colored*/) {
        convertView.setBackgroundColor(myColor);
    } else convertView.setBackgroundColor(defaultColor);
}