Drawing top border on a shape on Android

Marek Stój picture Marek Stój · Feb 8, 2010 · Viewed 39.5k times · Source

I'm creating a custom progress bar (positioned under a WebView) and what I would like to draw is a 1dp-wide line between the WebView and the ProgressBar. I'm modifying existing drawable, namely progress_horizontal.xml, and tried something like this:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

  (...)

  <item>
    <shape android:shape="line">
      <stroke android:width="1dp" android:color="#FF000000" />
    </shape>
  </item>

</layer-list>

This line however is vertically centered but I want it to be drawn on top of the drawable. The only idea I could come up with is to use this "hacky" gradient below:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

  (...)

  <item>
    <shape>
      <gradient
          android:startColor="#FF000000"
          android:centerColor="#00000000"
          android:centerY="0.01"
          android:endColor="#00000000"
          android:angle="270"
      />
    </shape>
  </item>

</layer-list>

Do you have better ideas how to draw a single line shape aligned to the top of the drawable defined with layer-list?

Answer

cottonBallPaws picture cottonBallPaws · Oct 24, 2010

I spent a while trying to figure this out as well. Hopefully there is a better way to do it but here is the method I used, which is also kind of hackish, but in case it helps someone, I thought I would share.

The first item in your layer list should be a solid of whatever color you want to be your border. Following that would be the thing(s) you want to have the border, with padding on whatever side you want the border to be on.

For example:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="YOUR BORDER COLOR" />
        </shape>
    </item>
    <item android:top="YOUR TOP BORDER THICKNESS">
        THE THING YOU WANT A BORDER ON
    </item>
</layer-list>

The idea is that the padding on the item reveals the solid shape behind it, giving the border appearance. You could add padding to any side to add a border. I imagine you could get more complicated and have different colored borders this way as well.

Seems like a hack but it worked for me.

EDIT: I said "padding" but in layer-lists it's more of an offset.