Search code examples
androidmaterial-designandroid-textinputedittext

Change TextInputEditText Hint Style


I want to change TextInputEditText type FilledBox

When before Typing hint needs style Bold and color #FF0000 (RED) When after Typing hint style regular and color #000000 (Black)

How Can I do


Solution

  • As Martin suggested, use a textWatcher on your EditText and override onTextChange to detect changes in your EditText. In this sample you need two font files in the assets folder in

    ...app\src\main\assets\arial.ttf

    and

    ...app\src\main\assets\arialbold.ttf

    //within your Activity: 
    Context context = getApplicationContext();
    int colorRed = context.getResources().getColor(R.color.red, null);
    int colorBlack = context.getResources().getColor(R.color.black, null);
    
    TextInputLayout textInputLayout = findViewById(R.id.textInputLayout);
    EditText tv_input               = findViewById(R.id.tv_input);
    
    textInputLayout.setTypeface(
        Typeface.createFromAsset(context.getAssets(), "arialbold.ttf"));
    
    ColorStateList colorStateListRed = ColorStateList.valueOf(colorRed);
    ColorStateList colorStateListBlack = ColorStateList.valueOf(colorBlack);
    
    tv_input.addTextChangedListener(new TextWatcher() {
    
        @Override
        public void beforeTextChanged(CharSequence s, int start, 
        int count, int after) {}
    
        @Override
        public void onTextChanged(CharSequence s, int start, 
        int before, int count) {
    
            if(s.length() > 0){
                textInputLayout.setDefaultHintTextColor(colorStateListBlack);
                textInputLayout.setTypeface(
                    Typeface.createFromAsset(
                        context.getAssets(), "arial.ttf")
                );
            }
    
            else{
                textInputLayout.setDefaultHintTextColor(colorStateListRed);
                textInputLayout.setTypeface(
                    Typeface.createFromAsset(
                        context.getAssets(),"arialbold.ttf")
                );
            }
        }
    
        @Override
        public void afterTextChanged(Editable s) {}
    });
    
    
    layout xml:
    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/textInputLayout"
        android:hint="@string/name"
        android:textColorHint="@color/red"
        android:layout_width="match_parent"
        android:layout_height="65dp">
    
        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/tv_input"
            android:textColor="@color/black"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:inputType="text"
            android:textColorHint="@color/red"
            android:textSize="16sp" />
    </com.google.android.material.textfield.TextInputLayout>
    

    Result: Result