Android textview font based on language

2019-08-12 17:16发布

问题:

Is there a general method for handling font like, if it is Chinese I use a custom font for it, if English then I fall back to the default font? Thanks.

回答1:

Here is my 2 cents. You can use Calligraphy library to change the custom font easily either for whole app or for specific TextView as well.

  • If you want to do it for whole app, then one solution I can think of is:

    1. In your app you can listen to the Broadcast of ACTION_LOCALE_CHANGED.
    2. Inside the listener check to see whether the locale is Locale.SIMPLIFIED_CHINESE or Locale.TRADITIONAL_CHINESE, then change the app's font.
  • If you want to programatically change font of lets say partial text then you can use CalligraphyTypefaceSpan as mentioned Multiple Typeface's per TextView / Spannables section:

    SpannableStringBuilder sBuilder = new SpannableStringBuilder();
    sBuilder.append("Hello!") // Bold this
    .append("I use Calligraphy"); // Default TextView font.
    // Create the Typeface you want to apply to certain text
    CalligraphyTypefaceSpan typefaceSpan = new 
    CalligraphyTypefaceSpan(TypefaceUtils.load(getAssets(), "fonts/Roboto-Bold.ttf"));
    // Apply typeface to the Spannable 0 - 6 "Hello!" This can of course by dynamic.
    sBuilder.setSpan(typefaceSpan, 0, 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    setText(sBuilder, TextView.BufferType.SPANNABLE);
    

Hope it helps.

P.S: I am not affiliated to the library in any way. I am a happy user of it.