1

我有一个ListView我想与一个一起使用ArrayAdapter来添加不同样式的行。这些行是在我的应用程序中的不同状态下创建的,并且根据不同的状态,应该对行进行样式设置(如颜色和内容)。

这是一些伪代码:

创作时:

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

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

mArrayAdapter.add("Message");

这很好用,消息会根据不同的状态在列表中弹出,但我希望行的样式不同。这该怎么做?ArrayAdapter是使用自定义 Add() 方法创建自定义的解决方案吗?

4

1 回答 1

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);
    }
}
于 2010-07-15T13:10:44.553 回答