作者:兜子
需求背景
产品有一个需求,分开设置EditText中 hint的字体大小和输入的字体大小,在Android原生的控件属性中,没有单独设置的方法。以下解决方案,部分使用kotlin语言。
解决方案
- 继承一个SpannableString,重写构造方法
public CustomHint(final Typeface typeface,final CharSequence source,final Integer style,final Float size){super(source);MetricAffectingSpan typefaceSpan = new CustomMetricAffectingSpan(typeface, style, size);setSpan(typefaceSpan, 0, source.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);}
- 在代码中单独设置hint文字以及大小
val customHint = CustomHint(Typeface.DEFAULT, "这里是Hint的文字",Typeface.NORMAL, AutoUtils.getPercentWidthSize(54).toFloat())etAbleWithdrawMoney.hint = customHint
需要注意的是,单独设置hint的大小之后,在小米的部分机型中会出现光标上移,也就是不居中的现象,这里我们还需要单独设置光标的大小和颜色。
定义一个drawable文件
<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"android:shape="rectangle"><size android:width="2dp" /><solid android:color="@color/color_bg_yellow" /><paddingandroid:bottom="60dp"android:top="0sp" /></shape>
然后在EditText的布局文件中添加属性即可
android:textCursorDrawable="@drawable/cursor"
