You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Kotlin:带虚线的推荐码输入EditText布局实现问题

实现带底部虚线的推荐码输入EditText

要实现你需要的底部虚线样式输入框,你之前的layer-list方案仅绘制了实线,未使用虚线核心属性,以下是正确的实现步骤:

1. 创建底部虚线背景Drawable

在drawable目录下新建et_dash_bottom.xml,通过layer-list将虚线定位到输入框底部,并用stroke属性定义虚线样式:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- 定位虚线到输入框底部:top值 = EditText高度 - 虚线宽度 -->
    <item
        android:top="53dp"
        android:left="0dp"
        android:right="0dp">
        <shape android:shape="rectangle">
            <!-- 定义虚线样式:宽度、颜色、线段长度、间隔 -->
            <stroke
                android:width="2dp"
                android:color="@color/green"
                android:dashWidth="8dp"
                android:dashGap="4dp" />
        </shape>
    </item>
</layer-list>
  • dashWidth:虚线中单个线段的长度
  • dashGap:线段之间的间隔
  • top属性计算:你的EditText高度是55dp,虚线宽度2dp,所以55-2=53dp,确保仅在底部显示虚线

2. 配置EditText布局

调整EditText的属性,应用上述背景,并优化输入体验:

<EditText
    android:id="@+id/code1"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:gravity="center"
    android:maxLength="1"
    android:textSize="18sp"
    android:padding="8dp"
    android:layout_marginEnd="4dp"
    android:imeOptions="actionNext"
    android:background="@drawable/et_dash_bottom"
    android:inputType="textNoSuggestions|textCapCharacters"
    android:textCursorDrawable="@null"
    android:layerType="software" />
  • android:layerType="software":解决Android 12及以上版本硬件加速导致虚线不显示的问题
  • android:textCursorDrawable="@null":让光标颜色与文字颜色一致,优化视觉效果
  • android:inputType="textNoSuggestions|textCapCharacters":关闭输入法联想,自动转为大写(可根据需求调整)

注意事项

  • 若需横向排列多个输入框,直接复制上述EditText代码,用LinearLayout或ConstraintLayout横向布局即可
  • 调整虚线颜色、粗细,修改stroke中的color和width属性即可

内容的提问来源于stack exchange,提问作者Sakthivel K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 13:47:35