学而实习之 不亦乐乎

Android 中实现虚线(一):通过资源文件实现

2024-01-06 21:03:09

一.水平虚线

在drawable下新建一个drawable资源文件dotted_line.xml,代码如下:

<?xml version="1.0" encoding="utf-8"?>
<shape  android:shape="line" xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke
        android:dashWidth="2dp"  //虚线的宽度
        android:dashGap="2dp"  //虚线间隔宽度
        android:color="@color/theme_color" //虚线的颜色
        android:width="1dp"/>  //宽度
</shape>

使用

<TextView
    android:background="@drawable/dotted_line"
    android:layerType="software"
    android:layout_width="300dp"
    android:layout_height="wrap_content"/>

上面是单线条,如果需要实现虚线边框效果的话,把 android:shape="line" 删掉就好了,或者将 line 改成 rectangle

二.垂直虚线

垂直虚线是在水平虚线的基础上进行一个90度的旋转就可得到,不过还是得做下处理。

再建一个drawable资源文件dotted_line_vertical.xml,代码如下:

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

    <item
        android:left="-300dp"
        android:right="-300dp">

        <rotate
            android:drawable="@drawable/dotted_line"  //引用水平虚线的drawable
            android:fromDegrees="90"/> //旋转90度
    </item>

</layer-list>

记住,这里一定得设置 left和 right 属性,如果不加会显示不出来

在页面上使用和水平一样通过background来使用,如下:

<TextView
    android:background="@drawable/dotted_line_vertical"
    android:layout_width="1dp"
    android:layout_height="300dp"/>