Search code examples
androidxmldrawable

Can you put a DrawableShape or Shape, "directly in" a layout?


In the main activity XML file of my app, I have a layout, with some ImageView:

<LinearLayout
..>
<ImageView
    .../>
<ImageView
    ..."/>
</LinearLayout>

No problem so far. Separately, I define blob.xml which is just a large white dot.

blob.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="#ff0000"/>
    <size android:width="32dp" android:height="32dp"/>
</shape>

Of course, I can put the blob "in" an ImageView like this:

<LinearLayout
..>
<ImageView
    .../>
<ImageView
    ..."/>
<ImageView
    android:src="@drawable/blob"
    .../>
</LinearLayout>

That's all fantastic. I'll never develop for iOS again! But is there a way to simply directly put a "shape" inside the layout XML? So, something like..

<LinearLayout
..>
<ImageView
    .../>
<ImageView
    ..."/>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="#ff0000"/>
    <size android:width="32dp" android:height="32dp"/>
</shape>
</LinearLayout>

or perhaps ...

<LinearLayout
..>
<ImageView
    .../>
<ImageView
    ..."/>
<ImageView
android:src={
   <shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="#ff0000"/>
    <size android:width="32dp" android:height="32dp"/>
   </shape>
   }
   >
</LinearLayout>

Or something like that!

Again, essentially "not using a separate drawable/ file"

Is this possible? Sorry, it's difficult to find this, as such, documented in Android.


Solution

  • No, it's not possible to define an inline Drawable (yet)


    Anyway, if you feel masochist, you can build a drawable in Java and then assign it to your View.
    But this, in my opinion, would be kind of an overkill.

    I only use this technique when forced.


    Further on (if you really feel depraved ;)), there's another technique which consists in making a custom View and override the onDraw method to completely draw it on your own.

    I use this technique only if I must build something really new (i.e.: some View not available among the standard ones), such as a rotating knob or a gauge or whatever.

    Kind of a pain, but it gives its results.