views:

412

answers:

1

Hello,

I have a ListView that I want to use with an ArrayAdapter to add different styled rows. The rows are created on different states in my application, and depending on the different states the rows should be styled(like colors and stuff).

Here is some pseudo-code:

on creation:

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

On different states, which is triggered by another thread using a MessageHandler, add a row to the list containing a message:

mArrayAdapter.add("Message");

This works fine, messages are popping up in the list depending on different states, but I want to have the rows styled differently. How to do this? Is the solution to create a custom ArrayAdapter with a custom Add() method?

/James Ford

+1  A: 

What you have to do is creating a custom ArrayAdapter and override the getView() method. There you can decide whether apply a different style to the row or not. For instance:

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);
    }
}
Cristian
Thanks,Works like a charm after som tweaking!
James Ford
Having some new problem with this. label.setTextColor() gets the whole label and sets the color for every row. It should just set the color on the new row, not on items already in the list.
James Ford