How to set font weight as light, regular in Android

自闭症网瘾萝莉.ら 提交于 2020-02-26 11:08:08

问题


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?


回答1:


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?




回答2:


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.



来源:https://stackoverflow.com/questions/31947165/how-to-set-font-weight-as-light-regular-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!