更改浮动标签EditText和TextInputLayout的字体

34

有人尝试更改浮动标签的字体吗?我已经更改了EditText的源代码,但是浮动标签的字体没有改变,非常感谢那些帮助我的人。

代码:

               <android.support.design.widget.TextInputLayout
                    android:id="@+id/tilTextoDescricao"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_toRightOf="@id/tilValorUnidade"
                    android:layout_marginTop="10dp">

                    <EditText
                        android:id="@+id/etTextoDescricao"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="5dp"
                        android:hint="Descrição"
                        android:textSize="15dp"
                        android:inputType="text" />

                </android.support.design.widget.TextInputLayout>

----------------- 

   etTextoDescricao= (EditText) findViewById(R.id.etTextoDescricao);
  etTextoDescricao.setTypeface(CustomTypeface.getTypefaceMediumDefault(this));

输入图像描述

12个回答

0
修复@adneal答案中的问题: 如果setErrorEnabled未设置为true,则mErrorView将为null,如果您在任何时候将其设置为false,则字体将恢复为默认值。 因此,要修复它:
在您的自定义TextInputLayout中覆盖setErrorEnabled。
@Override
public void setErrorEnabled(boolean enabled) {

    super.setErrorEnabled(enabled);

    if (enabled) {

        try {

            Field cthf = TextInputLayout.class.getDeclaredField("mErrorView");
            cthf.setAccessible(true);

            TextView error = (TextView) cthf.get(this);

            if (error != null)
                error.setTypeface(tf);


        } catch (Exception e) {

        }
    }
}

0
如果你也遇到了一个奇特的需求,只需要将自定义字体设置为浮动标签,而其他任何方法都无法实现,请尝试这个方法。至少对于材料库版本1.3.0-alpha03,这个方法对我有效。
@SuppressLint("RestrictedApi")
fun setHintFontFamily(view: TextInputLayout, fontRes: Int) {
    val font = ResourcesCompat.getFont(view.context, fontRes)!!

    try {
        val collapsingTextHelperField =
            view::class.java.getDeclaredField("collapsingTextHelper").apply {
                isAccessible = true
            }
        val collapsingTextHelper = collapsingTextHelperField.get(view) as CollapsingTextHelper

        collapsingTextHelper.collapsedTypeface = font
    } catch (e: Exception) {
    }
}

首先,我们像其他答案一样获取CollapsingTextHelper,但是然后我们使用它的属性collapsedTypeface,它似乎正好符合我们的需求——仅将字体应用于浮动标签。请注意,此属性的可见性受到库组的限制(这就是为什么我使用了@SuppressLint)。因此,实现细节可能会在未来发生变化。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接