2010-07-15 56 views
1

我有一个ListView,我想用ArrayAdapter添加不同样式的行。这些行是在我的应用程序的不同状态下创建的,并且根据不同的状态应该设置行的样式(如颜色和东西)。样式添加行到ArrayAdapter ListView Android

下面是一些伪代码:

上创造:

mArrayAdapter = new ArrayAdapter(this, R.layout.message); 
mView = (ListView) findViewById(R.id.in); 
mView.setAdapter(mArrayAdapter); 

在不同的状态,这是由使用的MessageHandler另一个线程触发,将行添加到包含消息列表:

mArrayAdapter.add("Message"); 

这工作正常,消息弹出列表根据不同的状态,但我想有不同的行风格。这个怎么做?使用自定义Add()方法创建自定义ArrayAdapter的解决方案是什么?

回答

1

您需要做的是创建自定义ArrayAdapter并覆盖getView()方法。您可以决定是否将不同的样式应用于该行。例如:

class CustomArrayAdapter extends ArrayAdapter { 
    CustomArrayAdapter() { 
     super(YourActivity.this, R.layout.message); 
    } 

    public View getView(int position, View convertView, 
              ViewGroup parent) { 
     View row=convertView; 

     if (row==null) {              
      LayoutInflater inflater=getLayoutInflater(); 

      row=inflater.inflate(R.layout.message, parent, false); 
     } 

     // e.g. if you have a TextView called in your row with ID 'label' 
     TextView label=(TextView)row.findViewById(R.id.label); 
     label.setText(items[position]); 

     // check the state of the row maybe using the variable 'position' 
     if(I do not actually know whats your criteria to change style){ 
      label.setTextColor(blablabla); 
     } 

     return(row); 
    } 
} 
+0

感谢, 作品像索姆的调整后的魅力! – 2010-07-15 13:52:11

+0

有一些新的问题。 label.setTextColor()获取整个标签并设置每一行的颜色。它应该只设置新行的颜色,而不是已经在列表中的项目。 – 2010-07-15 16:10:35

相关问题