I need to create a pattern to set as a background of some View
. I want the pattern to look something like this:
I don't want to import any image to drawable, but instead, I want to create my own shapes, layer-list and the ultimate goal is to have a pattern as a background.
Is is possible to achieve this without having to import any external image?
You can get a pattern of repeating tiles based upon shape drawables by creating a custom
View
and overridingonDraw()
.Let's start by creating the tile as a layer list made of shape drawables, in this case alternating squares of black and white:
my_background.xml
You need a method
drawableToBitmap()
to transform the tile into a Bitmap like here.Override
onDraw()
:Depending on the type of
View
, you may have to take additional steps.View
extending some kind ofLayout
, set theandroid:background
attribute to any color in order to trigger the call toonDraw()
View
s it may be easier to implement and at the same time better for performance to position your customView
below the otherView
(e.g. as two children in aRelativeLayout
) and make the sizes match.ImageView
you will need to draw the foreground drawable on top of the background pattern. In this case, you can modifyonDraw()
as follows:onDraw() preserving foreground drawable:
EDIT
As mentioned above, in some cases (e.g.
TextView
,ProgressBar
) you may want to use a workaround:View
background transparent.View
in the custom layout (set the layout width and height towrap_content
).