开发者

Styling added rows to ArrayAdapter ListView Android

开发者 https://www.devze.com 2023-01-07 02:21 出处:网络
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 shoul

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 usin开发者_开发知识库g 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?


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);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消