Modify the font family used in the EditText setError() method

Is there a way to modify the font-family of the text displayed in the EditText setError() method?

I attempted the following solution:

editText.setError(Html.fromHtml("<span style=\"font-family: sans-serif !important\">hello</span>"));

I am looking to customize the font family for error messages specifically on Samsung mobile devices, especially when the user has chosen a different font elsewhere.

If anyone has any suggestions or ideas on how to achieve this, I would greatly appreciate it.

Thank you in advance!

Answer №1

Here is a suggestion for you to try:

Typeface customTypeFace = Typeface.createFromAsset(getAssets(), "BYekan.ttf");

TextInputLayout inputLayout = (TextInputLayout) view.findViewById(R.id.lyt_input); 

SpannableStringBuilder ssbuilder = new SpannableStringBuilder(getString(R.string.err_wrong_input));
ssbuilder.setSpan(new CustomTypefaceSpan("", ActivityMain.customTypeFace), 0, ssbuilder.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);    
inputLayout.setError(ssbuilder);

Make sure you have added the following file to your project as well:

public class CustomTypefaceSpan extends TypefaceSpan {

    private final Typeface newType;

    public CustomTypefaceSpan(String family, Typeface type) {
        super(family);
        newType = type;
    }

    @Override
    public void updateDrawState(TextPaint ds) {
        applyCustomTypeFace(ds, newType);
    }

    @Override
    public void updateMeasureState(TextPaint paint) {
        applyCustomTypeFace(paint, newType);
    }

    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);
    }
}

Answer №2

1)Implement the following class:

import android.graphics.Paint;
import android.graphics.Typeface;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextPaint;
import android.text.style.TypefaceSpan;

public class CustomTypefaceSpan extends TypefaceSpan {
public static final Parcelable.Creator<CustomTypefaceSpan> CREATOR = new Parcelable.Creator<CustomTypefaceSpan>() {

    public CustomTypefaceSpan createFromParcel(Parcel in) {
        return new CustomTypefaceSpan(in);
    }

    public CustomTypefaceSpan[] newArray(int size) {
        return new CustomTypefaceSpan[size];
    }
};
private final Typeface newType;

public CustomTypefaceSpan(String family, Typeface type) {
    super(family);
    newType = type;
}

private CustomTypefaceSpan(Parcel in) {
    super(in.readString());
    newType = Typeface.createFromFile(in.readString());
}

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);
}

@Override
public void updateDrawState(TextPaint ds) {
    applyCustomTypeFace(ds, newType);
}

@Override
public void updateMeasureState(TextPaint paint) {
    applyCustomTypeFace(paint, newType);
}

}

2)Integrate this code into your activity:

Typeface typeFaceDefault = Typeface.createFromAsset(getAssets(), "yourFont.ttf");

3)Include this method in your activity:

   public void setErrText(CharSequence err, EditText view){
    SpannableStringBuilder ssbuilder = new SpannableStringBuilder(err);
    ssbuilder.setSpan(new CustomTypefaceSpan("", typeFaceDefault), 0, ssbuilder.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
    view.setError(ssbuilder);
}

4)Finally, utilize it like so:

setErrText(getString(R.string.your_err_txt), yourEdt);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Resizing webpages for mobile devices results in misaligned rows

I'm currently using Bootstrap on a website and encountering issues with the responsiveness of rows on mobile devices. The desired outcome is for rows to be divided into 4 equal sections per row on larger screens, then scale down to 2 equal sections p ...

Create a stunning Bootstrap carousel that showcases images perfectly centered and automatically resized in both width and height to fit the Div container

Currently, I am working on integrating a Bootstrap carousel that features centred and auto-resized images. In the JSFiddle example provided (https://jsfiddle.net/koba1/mb94dgzu/6/), you will notice that the first image (a vertical one) stretches to fill th ...

Linking the location of the pop-up to the currently selected text box

I am currently experimenting with setting the top and left values relative to the selected_element (which is active at the time of triggering the popup) in a manner similar to a tooltip. I attempted to use $().position() in combination with jQuery, but it ...

Exploring the design and aesthetic elements of a background image

After reviewing the documentation, I came across this statement: "A style can specify properties such as height, padding, font color, font size, background color, and much more." This got me thinking, what exactly does "much more" entail? Could it mean tha ...

What is the process of activating an event when the user taps outside of an EditText field?

I need help with creating an app that can detect when a user has entered text into an editText and then clicks away from it or closes the keyboard. Can anyone provide guidance on how to achieve this? My Java skills are limited, so I would appreciate any d ...

Is there a way for me to position my arrow beside the header while still keeping the toggle function intact?

Can anyone assist me in positioning my arrow next to the header text, which I toggle on click? I attempted placing the arrow <div> into the H1 tag, but then the toggle function stops working. Any help would be greatly appreciated! Please includ ...

Comparison between Android's connection to a Remote MySQL database using JDBC or JSONIn

Optimizing the use of JDBC requires a strong, low latency high-bandwidth connection. Utilizing a PHP service could provide better results in some cases. In my current project, developing a Restaurant menu app that must retrieve data from a server-based da ...

Ways to make text within a container smoothly slide down

Hello, I have a question about jQuery as I am relatively new to it. I am currently working on creating a team members section where clicking on a team member will slide down information about that person underneath. I have managed to set up the parent co ...

How to strategically break Bootstrap 5 button groups for different resolutions?

Is there a way to create a line break in a specific place within a button group on a certain screen size? I have a button group with 4 buttons in a row, and I would like to split it into two lines after the first button if there isn't enough space. ...

Encountering an issue while attempting to launch my application on an Android device

E/unknown:ReactNative: Exception in native call java.lang.IllegalStateException: Native module AudioRecorderManager tried to override AudioRecorderManager. Check the getPackages() method in MainApplication.java, it might be that module is bein ...

The div element is not expanding as expected, causing the content to overlap

In my code, I have a portfolio-container div with two images and paragraphs inside a list element. The issue I'm facing is that the div is not expanding vertically, causing the images and paragraphs to overlap with the footer below. I've attempte ...

"Enhance your website with a dynamic carousel feature using Twitter Bootstrap's JavaScript

After researching various examples, I noticed that most of them only display one Item at a time. I want to have multiple active items displayed using thumbnails, but the examples I found show that the Item itself contains multiple thumbnails inside of it. ...

Stop the page from scrolling

I'm trying to find a way to disable page scrolling, so I used this style for the body: overflow: hidden; Surprisingly, it worked perfectly on desktop but had no effect on mobile devices. After checking out this resource, it seems that creating a ch ...

What is the best way to create space between three columns in Bootstrap?

Despite my efforts to find a solution on Stackoverflow, I have not been able to locate exactly what I need. I am trying to evenly space and center three columns across my page. However, when I assign col-md-4 to each column, they end up too close together ...

A guide on incorporating a component from a nested directory with webpack

https://i.sstatic.net/kLB0S.png The directory structure above shows how my react app 'MyProject' is organized. Using this structure, I successfully utilize the Layout component in Main.jsx (located at src/Main.jsx) by : import Layout from &apo ...

An issue in cordova android related to cross-domain restrictions

My small cordova app utilizes beacon plugins to send a get request to a specific page once beacons are discovered. However, I have been facing issues with sending the get request to my server using the code snippet below with jsonp. Despite trying out di ...

The title on my iOS app is off-center towards the left side

My title in the application is not centered on iPhone, but it appears fine when accessed through a browser. How can I fix this issue? Here is my HTML code: <div data-view="Moobile.ScrollView" class="component-testpage-view"> <div data-role="n ...

Tips for verifying the presence of a reply

I have developed an application that makes a call to a specific phone number. If the number does not respond, the application performs a certain action. My question is: how can I determine if there is a response or not? Below is the code snippet: PhoneCa ...

What is the best way to align labels and textboxes next to each other when resizing?

I am facing an issue with screen resizing. The code below appears fine on a full screen, but as soon as I resize the window even a tiny bit, it starts to look distorted and unattractive. I have gone through the Bootstrap 4 grid layout tutorial, but it is n ...

Incorporating a scrollbar into a CSS content accordion for enhanced user experience

Currently, I am exploring a tutorial for coding a content accordion which can be found here: I am wondering about the possibility of adding endless content to each section while incorporating a scroll bar. Any suggestions on how to achieve this? Apprecia ...