Change font of the floating label EditText and TextInputLayout

前端 未结 12 1095
北海茫月
北海茫月 2020-12-03 01:23

Someone tried to change the font of the floating label? I changed the source of EditText but the font of the floating label did not change, I am very grateful to those who h

12条回答
  •  孤街浪徒
    2020-12-03 01:41

    Here is a custom class implementation for adneal's answer.

    public class CustomTextInputLayout extends TextInputLayout {
    
        public CustomTextInputLayout(Context context) {
            super(context);
            initFont(context);
        }
    
        public CustomTextInputLayout(Context context, AttributeSet attrs) {
            super(context, attrs);
            initFont(context);
        }
    
        private void initFont(Context context) {
            final Typeface typeface = Typeface.createFromAsset(
                    context.getAssets(), "fonts/YOUR_CUSTOM_FONT.ttf");
    
            EditText editText = getEditText();
            if (editText != null) {
                editText.setTypeface(typeface);
            }
            try {
                // Retrieve the CollapsingTextHelper Field
                final Field cthf = TextInputLayout.class.getDeclaredField("mCollapsingTextHelper");
                cthf.setAccessible(true);
    
                // Retrieve an instance of CollapsingTextHelper and its TextPaint
                final Object cth = cthf.get(this);
                final Field tpf = cth.getClass().getDeclaredField("mTextPaint");
                tpf.setAccessible(true);
    
                // Apply your Typeface to the CollapsingTextHelper TextPaint
                ((TextPaint) tpf.get(cth)).setTypeface(typeface);
            } catch (Exception ignored) {
                // Nothing to do
            }
        }
    }
    

    In your XML files now you need to use CustomTextInputLayout instead of TextInputLayout and it will work out of the box.

    
    
        
    

    Thanks adneal for the answer.

提交回复
热议问题