作者:兜子

需求背景

产品有一个需求,分开设置EditText中 hint的字体大小和输入的字体大小,在Android原生的控件属性中,没有单独设置的方法。以下解决方案,部分使用kotlin语言。

解决方案

  1. 继承一个SpannableString,重写构造方法
  1. public CustomHint(final Typeface typeface,
  2. final CharSequence source,
  3. final Integer style,
  4. final Float size){
  5. super(source);
  6. MetricAffectingSpan typefaceSpan = new CustomMetricAffectingSpan(typeface, style, size);
  7. setSpan(typefaceSpan, 0, source.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
  8. }
  1. 在代码中单独设置hint文字以及大小
  1. val customHint = CustomHint(Typeface.DEFAULT, "这里是Hint的文字",
  2. Typeface.NORMAL, AutoUtils.getPercentWidthSize(54).toFloat())
  3. etAbleWithdrawMoney.hint = customHint
  1. 需要注意的是,单独设置hint的大小之后,在小米的部分机型中会出现光标上移,也就是不居中的现象,这里我们还需要单独设置光标的大小和颜色。

  2. 定义一个drawable文件

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <shape xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:shape="rectangle">
  4. <size android:width="2dp" />
  5. <solid android:color="@color/color_bg_yellow" />
  6. <padding
  7. android:bottom="60dp"
  8. android:top="0sp" />
  9. </shape>

然后在EditText的布局文件中添加属性即可

  1. android:textCursorDrawable="@drawable/cursor"