36

I have this difficulty to have both rounded corner and a background image in my LinearLayout.

I know I can achive the rounded corner by using the shape drawable XML, but if I put the shape drawable as the background of my LinearLayout with android:background=@drawable/rounded_corner then I cannot assign any image to be used as a background.

How can I get both a rounded corner with a background image in my LinearLayout? Any help would be appreciated. Thanks!

Surya Wijaya Madjid
  • 1,823
  • 1
  • 19
  • 25

2 Answers2

35

You could use LayerDrawable, which could contain as many layers(shapes or images) as you need. You can create it either as resource or programmatically.

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/rounded_corners" android:id="@+id/rounded_corners"/>
    <item android:drawable="@drawable/additional_image" android:id="@+id/additional_image" />
</layer-list>
woodshy
  • 4,085
  • 3
  • 22
  • 21
  • 2
    Thanks for the answer woodshy :) I tried it but it doesn't work like what I expected. They're just being put on top of each other and the corner part from the background image is still visible behind the rounded corner shape. Any idea how to make it to use the background image while maintaining the rounded corner shape? – Surya Wijaya Madjid Jun 07 '11 at 11:01
  • so why can't you create an image with rounded corners? – woodshy Jun 07 '11 at 11:43
  • 4
    That would be the easiest way, but I want to avoid that if I could. The fact is, the image is made by someone else and if it's possible I want to do it without requesting him to change the image itself. – Surya Wijaya Madjid Jun 07 '11 at 13:05
  • This worked for me as I wanted an image inside a circle, the circle is an xml shape with a 30dp for all corners and the image is just a drawable. – speedynomads Jul 23 '13 at 14:30
  • I find that the first layer (a shape) is scaled up when the second layer (an image) is added. The image is smaller than the shape. Is this normal? How can I avoid it? – Roar Skullestad Sep 12 '13 at 10:39
3

for those who seeks a different answer

in the xml

<string-array name="ulke_isimleri">
    <item>kan</item>
    <item>kebapeli</item>
</string-array>

<array name="ulke_gorselleri">
    <item>@drawable/kan1</item>
    <item>@drawable/esyalar_kebap_adana</item>
</array>

in the oncreate or general

 String[] ulkeAdlari =getResources().getStringArray(R.array.ulke_isimleri);
 TypedArray ulkeGorselleri = getResources().obtainTypedArray(R.array.ulke_gorselleri);

as a function

 @Override
    public Drawable getDrawable(int position) {

         Drawable[] drawable = new Drawable[] { 
                 ulkeGorseli.getDrawable(position   ) 
                 ,
                 new TextDrawable(ulkeAdlari[ position   ]  )
         };
        return new LayerDrawable(drawable);
    }
Alp
  • 1,863
  • 1
  • 20
  • 38