样式添加行到ArrayAdapter ListView Android

我有一个ListView ,我想与ArrayAdapter一起使用来添加不同的样式行。 行在我的应用程序中的不同状态下创建,并根据不同的状态行样式(如颜色和东西)。

这是一些伪代码:

在创作:

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

在使用MessageHandler的另一个线程触发的不同状态下,向包含消息的列表添加一行:

 mArrayAdapter.add("Message"); 

这工作正常,消息在列表中弹出取决于不同的状态,但我希望行的样式不同。 这个怎么做? 解决方案是使用自定义Add()方法创建自定义ArrayAdapter吗?

您要做的是创建一个自定义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); } // eg 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); } }