How to set font weight as light, regular in Androi

2020-06-06 17:41发布

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条回答
够拽才男人
2楼-- · 2020-06-06 18:03

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?

查看更多
Emotional °昔
3楼-- · 2020-06-06 18:06

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.

查看更多
登录 后发表回答