在运行时设置字体,Textview

isc*_*ers 39 fonts android textview

如何将字体设置为在运行时创建的textview?

我创建了textview

Textview tv = new TextView(this);      
tv.setTextSize(20);
Run Code Online (Sandbox Code Playgroud)

就像我可以改变
我希望将字体样式设置为"Verdana"的大小.

这该怎么做??尊重希什尔

Par*_*ani 68

在运行时设置内置字体:

  • 首先,要更改Font-face,使用Typeface类.

  • 现在,at Run-Time要设置font-face,请使用setTypeface(Typeface)Java代码

  • at Design-Time,设置font-face,使用 android:typeface="serif"

例如:

<TextView android:text="@+id/TextView01"
 android:id="@+id/TextView01"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:textSize="30px"
 android:textStyle="italic"
 android:typeface="serif" />
Run Code Online (Sandbox Code Playgroud)

在Android应用程序中设置自定义字体

要执行此操作,只需在项目根目录中创建资产/文件夹,并将字体(以TrueType或TTF格式)放入资产中.例如,assets/fonts/您可以在其中创建并放置TTF文件:

  TextView tv=(TextView)findViewById(R.id.custom); 
  Typeface face=Typeface.createFromAsset(getAssets(), "fonts/HandmadeTypewriter.ttf"); 
  tv.setTypeface(face); 
Run Code Online (Sandbox Code Playgroud)

  • 字体扩展可以是大写TTF或小写ttf,它只需要匹配资产文件夹中的方式 (7认同)

小智 5

您可以在资产文件夹中使用 .ttf 字体。假设字体的名称是“default.ttf”,您现在必须编写以下 2 行代码

TextView text = new TextView(this);
text.setTypeface(Typeface.createFromAsset(getAssets(), "default.ttf"));
Run Code Online (Sandbox Code Playgroud)

你也必须小心,因为不同的字体有不同的大小。您可能需要将大小设置为:

text.setTextSize(20);
Run Code Online (Sandbox Code Playgroud)


小智 5

您可以使用您存储在字体“res/font”中的字体,例如。适用于 API 级别 16 及以上。

   Typeface typeface = ResourcesCompat.getFont(context, R.font.rubik_medium);
   txtView.setTypeface(typeface);
Run Code Online (Sandbox Code Playgroud)

你也可以使用

   Typeface typeface = getResources().getFont(R.font.rubik_medium);
   txtView.setTypeface(typeface);
Run Code Online (Sandbox Code Playgroud)

但它支持 API 级别 26 及以上。