Android Drawable: Specifying shape width in percent in the XML file? Android Drawable: Specifying shape width in percent in the XML file? android android

Android Drawable: Specifying shape width in percent in the XML file?


You can't specify a percentage. You need to specify a Dimension value to it.

android:width is defined here: http://developer.android.com/reference/android/R.attr.html#width :

(emphasis mine)

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters).

For a definition of each dimension type, see: http://developer.android.com/guide/topics/resources/more-resources.html#Dimension

You will need to create your own attribute (see styleable) and perform the calculations yourself in onDraw(...).

See these two questions and the links therein for examples:


there is no true percentage setting, but you might get close.

it seems like the easiest way to achieve this is to use an image as your background drawable and just do a black and white split image.

the only other way I know to split anything is to use 2 views, each with its own bg color, and each given the same positive value for android:layout_weight attribute (ie. 50/50). they will then split the available space.

hope this helps!


The way I found to do this was by creating my own class inheriting from RelativeLayout, where I override the onMeasure method. At this stage, the height of the view is known, so I fetched the background, and manually set the inset of the items using setLayerInset.

    LayerDrawable bg = (LayerDrawable)getBackground();    int h = getMeasuredHeight();    bg.setLayerInset(1, 0, 0, 0, h/2);

This method is a bit cumbersome though. In most cases, the answer provided by chris should be sufficient.