views:

161

answers:

1

Hi!

I have a ListView and an adapter that sets alternating background colors to the list items overwriting getView Method in my adapter.

I want to go further and I would to set to each row a Resource background. I try in getView call the method setBackgroundResource:

private int[] messages = new int[] {R.layout.message,R.layout.message2};
//...
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
int MessagePos = position % messages.length;
v.setBackgroundResource(messages[MessagePos]);
return v;}

But this not work, and I the message throws by exception is File res/layout/message.xml from drawable resource ID #0x7f030004

Any ideas?

Thanks!

+1  A: 

You can't set a layout file to be the background resource. Background resource is for an image file. What you want is either to be inflating a different layout file depending on the position or to set the background color like so:

int colors = {0xFFFF0000, 0xFF0000FF};
v.setBackgroundColor(colors[MessagePos]};

The two colors listed are bright red and bright blue. If you aren't familiar with how those colors are defined, look up HTML color codes.

Inflating different layout files isn't hard, but takes a more code. Basically it comes down to getting a LayoutInflater from your context, and then calling inflater.inflate(context.getResources(), R.layout. .....);. There are plenty of good tutorials if you Google around for them.

Steve H
Sorry, I didn't have time to view the solution and now I'm trying using inflate and seems to work!, but the text in the view disappears, it's the first intent and I guess if I store the text before inflates the view can work, so I keep trying.A lot of thanks!!
Fran
@Fran: The text shouldn't disappear - it will just get reset to whatever is set by default in the layout file. If you're having trouble, edit your question to show what you're doing. Or if you've solved it all, click the tickmark next to this answer to say the problem is solved :)
Steve H
I save the text before inflate, and then set it later, sorry I didn't know about tickmark.
Fran