Search code examples
androidxmlandroid-layoutandroid-styles

How to set the font of TextInputEditText in theme.xml?


I want to apply the font to multiple TextInputEditTexts in common using style.

However, there is TextInputLayout in parent, but TextInputEditText cannot be found. (Even if the font is applied to TextInputLayout, the font of TextInputEditText does not change).

Can't TextInputEditText be inherited?

Should I just extend EditText to define the style?

<resources xmlns:tools="http://schemas.android.com/tools">
 
    <style name="SignInEditTextStyle" parent="Widget.MaterialComponents.TextInputLayout.OutlinedBox">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:minWidth">245dp</item>
        <item name="android:maxWidth">488dp</item>
    </style>
</resources>
<com.google.android.material.textfield.TextInputLayout
        android:id="@+id/login_pwd"
        style="@style/LogInEditTextStyle"
        android:layout_marginTop="100dp"
        android:hint="PWD"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/login_id">

        <com.google.android.material.textfield.TextInputEditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
          />
    </com.google.android.material.textfield.TextInputLayout>

Solution

  • Looking at the source code for TextInputEditText, it appears that the "parent" style you're looking for is named Widget.Design.TextInputEditText:

    ThemeEnforcement.obtainStyledAttributes(
        context,
        attrs,
        R.styleable.TextInputEditText,
        defStyleAttr,
        R.style.Widget_Design_TextInputEditText); // <--- this style
    

    Alternatively, you could leverage the "default style attribute":

    public TextInputEditText(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, R.attr.editTextStyle);
    }
    

    You would do this by creating a style of your choice, and then referencing that in your activity's theme:

    <style name="YourActivityTheme">
        <item name="editTextStyle">@style/YourEditTextStyle</item>
    </style>
    
    <style name="YourEditTextStyle">
        <item name="android:minWidth">245dp</item>
        <item name="android:maxWidth">488dp</item>
    </style>