【发布时间】:2012-09-23 15:47:15
【问题描述】:
如何在 Android TextView 中更改字体类型?
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Welcome!"
android:textSize="20sp" />
【问题讨论】:
标签: android
如何在 Android TextView 中更改字体类型?
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Welcome!"
android:textSize="20sp" />
【问题讨论】:
标签: android
您可以使用android:typeface 属性。例如:
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Welcome!"
android:typeface="sans"
android:textSize="20sp" />
XML 属性仅允许值 normal、sans、serif 和 monospace。如果您想使用不同的Typeface(可能是您的应用附带的自定义),您必须在加载 TextView 后调用 setTypeface() 以在代码中执行此操作。
【讨论】:
TypeFace.createFrom... 方法之一(如@Siddharth 描述的)加载它。
要添加到 Ted Hopp 的 答案中,如果您正在查看 TextView 的自定义字体,请在您引用 TextView 的 Activity 中使用此代码示例:
Typeface blockFonts = Typeface.createFromAsset(getAssets(),"ROBOTO-MEDIUM_0.TTF");
TextView txtSampleTxt = (TextView) findViewById(R.id.your_textview_id);
txtSampleTxt.setTypeface(blockFonts);
不过,在您使用它之前,您需要将您选择的字体复制到 assets 文件夹中。
您还可以查看我在 SO 上的answer 之一,其中有几个网站可用于下载字体。它们是:
【讨论】:
"fonts/"开头的路径作为你正在做的资产名称,你只需要创建一个fonts子文件夹。字体也可以从根 assets 文件夹中加载。
您可以通过将字体文件 (example.tff) 样式放置在 资产/字体,然后将您自己的字符串输入到 fontpath 变量中
String fontPath="fonts/Unkempt-Regular.ttf";
TextView aboutus=(TextView)findViewById(R.id.aboutus);
Typeface type=Typeface.createFromAsset(getAssets(), fontPath);
aboutus.setTypeface(type);
【讨论】: