将XML可绘制背景与视图底部对齐 [英] Align XML drawable background to bottom of view

查看:119
本文介绍了将XML可绘制背景与视图底部对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为TextView标头提供简单的纯色下划线.我希望这是可重用的,并且无论高度如何,将来都可以用于任何视图.我正在尝试使用背景可绘制对象,因此我可以简单地将其应用到视图中.我可以画一条线没有任何问题:

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?

推荐答案

这可以使用gradientDrawable实现.在这里,您去了:

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>

增加/减少centerX以增加/减少下划线的宽度.更改startColor更改下划线的颜色.

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

说明:

angle是渐变的角度.从左到右为0. 90是从下到上.

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

startColor是渐变的起始颜色.我们的角度是90度,所以渐变从底部开始(因此看起来像是下划线)

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是透明的centerColor.

centerColor is the centerColor which is transparent.

centerX是渐变的X位置,是宽度的一部分.使其较小(< 0.1),以获得更好的下划线.高于0.1的值看起来都很糟糕(尽管没有人阻止您!).

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

这篇关于将XML可绘制背景与视图底部对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆