Android设置字体样式
时间: 2023-11-02 10:17:23 浏览: 55
在 Android 中设置字体样式有两种方式:通过代码设置和通过 XML 布局文件设置。
1. 通过代码设置字体样式:
可以通过在 Java 代码中使用 Typeface 类来设置字体样式。以下是示例代码:
```java
TextView textView = findViewById(R.id.text_view);
Typeface typeface = Typeface.createFromAsset(getAssets(), "font/custom_font.ttf");
textView.setTypeface(typeface);
```
其中,"font/custom_font.ttf" 是自定义字体文件的路径。
2. 通过 XML 布局文件设置字体样式:
在 XML 布局文件中,可以使用 android:typeface 属性来设置字体样式。以下是示例代码:
```xml
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:typeface="monospace" />
```
其中,android:typeface 属性可以取以下值:
- normal:普通字体
- sans:无衬线字体
- serif:衬线字体
- monospace:等宽字体
如果需要设置自定义字体样式,可以将字体文件放在 assets 目录下,并使用以下代码:
```xml
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:typeface="file:///android_asset/font/custom_font.ttf" />
```
其中,"file:///android_asset/font/custom_font.ttf" 是自定义字体文件的路径。