How to set font weight as light, regular in Android

后端 未结 2 913
遇见更好的自我
遇见更好的自我 2021-02-11 14:28

I have 3 text views. I need to set their weight as Light, Regular and Condensed. Can someone help me on how to achieve this in Android?

相关标签:
2条回答
  • 2021-02-11 14:56

    You can only show a TextView as Light, Regular and Condensed if the font that you're referencing allows those styles.

    For example, if you import a font into your project and it doesn't have Light or Condensed, I don't think it's (dare I say) possible to make the text appear with that style in your TextView. If you are importing your own font, work with it programmatically e.g. In your activity declare a global TextView:

    private TextView tv;
    

    Then in onCreate(), reference the fontfile you save in /assets:

    Typeface someFontName-condensed = Typeface.createFromAsset(getAssets(), "assets/NameOfFont-condensed.ttf");
    
    tv = (TextView) findViewById(R.id.myTextViewId);
    tv.setTypeface(someFontName-condensed);
    

    Notice that I imported the condensed version of my font file (as .ttf), not as a packaged font .ttc. You can bring in various style versions of a font, but you should bring them in as individual .ttf files instead of one packaged file because you will want to reference the specific style .ttf.

    However, if you're using a system font that allows you to reference various styles from your xml, see what they say here:

    Valid values for android:fontFamily and what they map to?

    As they say, for something like Roboto, you'll use the fontFamily.

    0 讨论(0)
  • 2021-02-11 15:07

    Use android:textStyle on a TextView to set the text style like bold, italic or normal.

    Here is an example of a TextView with a bold text style:

    <TextView
      android:id="@+id/hello_world"
      android:text="hello world"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textStyle="bold"/>
    

    If you want to use light or condensed, you will have to change your font. You can do it like this:

    android:fontFamily="sans-serif-light"
    

    For more information about fonts, please also look at the following answer Valid values for android:fontFamily and what they map to?

    0 讨论(0)
提交回复
热议问题