EditText 行间距 以及光标高度和样式

本文介绍了如何在Android中调整EditText的行间距,包括使用lineSpacingMultiplier和lineSpacingExtra属性。同时,针对行间距增大后导致的光标高度过高问题,提出了通过自定义textCursorDrawable并在XML中设置padding来修正光标高度的方法,以保持文字居中显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

android:lineSpacingMultiplier="1.2" -- 设定行高为标准行高的1.2倍
android:lineSpacingExtra="20dp" -- 设定行高在标准行高的基础上再增加 20 dp

<EditText
android:id="@+id/cake"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/toolbar"
android:gravity="top"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:textSize="12sp"
android:lineSpacingMultiplier="1.2"
android:background="@android:color/holo_orange_light"
android:textColor="@android:color/white"
android:textCursorDrawable="@drawable/cursor"
android:hint="Type here..." />

当设定的行高大于标准行高之后
会出现光标的高度要比文字高度高的问题
如图所示:

这个问题的解决方法是:
在自定义的光标样式文件中对光标样式加以特殊处理
android:textCursorDrawable="@drawable/cursor"


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

<size android:width="1dp" />

<solid android:color="@android:color/white" />
<padding
android:top="1sp"
android:bottom="-3sp" />
</shape>

top = 1sp 这个会让光标向上多延伸 1 sp 的高度
bottom = -3sp 这个会让光标在下面缩短 3sp 的高度

这两个值不是固定的。
需要根据你设定的行间距来做调整。

调整后的效果如下:(1.2倍的行高,设定 cursor 的top = 0sp, bottom = -3sp)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值