change font for editText hint

后端 未结 10 2477
野趣味
野趣味 2020-12-03 13:17

Is it possible to change the font for the hint displayed in the EditText field? I want to set the font in the xml itself.

10条回答
  •  时光说笑
    2020-12-03 13:58

    You can change it with a SpannableString and a Custom TypefaceSpan.

    First, create a Custom TypefaceSpan class:

    public class CustomTypefaceSpan extends TypefaceSpan {
        private final Typeface mNewType;
    
        public CustomTypefaceSpan(Typeface type) {
            super("");
            mNewType = type;
        }
    
        public CustomTypefaceSpan(String family, Typeface type) {
            super(family);
            mNewType = type;
        }
    
        @Override
        public void updateDrawState(TextPaint ds) {
            applyCustomTypeFace(ds, mNewType);
        }
    
        @Override
        public void updateMeasureState(TextPaint paint) {
            applyCustomTypeFace(paint, mNewType);
        }
    
        private static void applyCustomTypeFace(Paint paint, Typeface tf) {
            int oldStyle;
            Typeface old = paint.getTypeface();
            if (old == null) {
                oldStyle = 0;
            } else {
                oldStyle = old.getStyle();
            }
    
            int fake = oldStyle & ~tf.getStyle();
            if ((fake & Typeface.BOLD) != 0) {
                paint.setFakeBoldText(true);
            }
    
            if ((fake & Typeface.ITALIC) != 0) {
                paint.setTextSkewX(-0.25f);
            }
    
            paint.setTypeface(tf);
        }
    }
    

    Then just set the TypefaceSpan to a SpannableString:

    TypefaceSpan typefaceSpan = new CustomTypefaceSpan(typeface);
    SpannableString spannableString = new SpannableString(hintText);
    
    spannableString.setSpan(typefaceSpan, 0, spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    

    And finally just set the hint of your EditText:

    mEditText.setHint(spannableString);
    

提交回复
热议问题