Align XML drawable background to bottom of view

亡梦爱人 提交于 2019-12-25 01:34:53

问题


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?


回答1:


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!).



来源:https://stackoverflow.com/questions/52430696/align-xml-drawable-background-to-bottom-of-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!