Search code examples
androidviewhierarchy

Android: How I can I add a background image to a GridLayout?


I have a GridLayout full of buttons - similar to a calculate with spaces between the buttons. I wants to skin the background including the those areas between the buttons but not the buttons themselves.

What is the best way to do this? Is there a means of setting a background image on the GridLayout itself or do I need to create a View hierarchy?

I had started experimenting thinking that child Views can be added to parent Views but it would appear that you can only add Views to ViewGroup derived classes?

Without a background, I'm dynamically constructing my GridLayout and adding it to the activity's default layout using setContentView( gridLayout ).

How would I go about doing this please?

EDIT: What I would really like to understand is how to compose complex view hierachies. It also appears the simple approach of gridLayout.setBackground() requires API 16 and I'm using API 14 for my devices too.


Solution

  • GridView is derived from View class. The View class has a method called void setBackgroundResource (), you can call it on your grid view object, pass an id of a drawable resource to it. This method was introduced since API level 1, so you don't have to worry about API compatibility issues.