RedBassett
RedBassett

Reputation: 3587

Align XML drawable background to bottom of view

I am trying to provide a simple solid-color underline to a TextView header. I want this to be reusable and to work with any view in the future, regardless of height. I am trying to favor a background drawable so I can simply apply it to view. I can draw a line without any problem:

<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:shape="line"
    >

     <stroke
        android:color="#8a9299"
        android:width="1dp"
        />

</shape>

This line is, however, centered in the background of the view. I see a bunch of online tutorials that use layers to draw a background-colored rectangle and then "peek" another rectangle from behind, however I don't know what background color this header element type will be used on, and transparent rectangle backgrounds show the color rectangle below. Is there any way to stick to a line but give it a bottom gravity inside the view it is applied to?

Upvotes: 0

Views: 230

Answers (1)

nupadhyaya
nupadhyaya

Reputation: 1944

This can be achieved using gradientDrawable. Here you go:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
    android:angle="90"
    android:startColor="#000000"
    android:centerColor="@android:color/transparent"
    android:centerX="0.1" />
</shape>

Increase/Decrease centerX to increase/decrease width of your underline. Change startColor to change the color of the underline.

Explanation:

angle is the angle of the gradient. 0 is left to right. 90 is bottom to top.

startColor is the start color of the gradient. Our angle is 90 so the gradient starts from bottom (and so it appears like an underline)

centerColor is the centerColor which is transparent.

centerX is the X position of the gradient as a fraction of the width. Keep it small (<0.1) for a good looking underline. Anything above 0.1 looks bad (nobody is stopping you though!).

Upvotes: 2

Related Questions