在Android系统中可以很方便的修改字体样式。系统提供了三种样式,分别是sans,serif,monospace。可以在xml布局文件中通过
android:typeface="[sans,serif,monospace]"
当然Android也为开发者提供了使用外部字体样式的方式。在官方给出的Design帮助文档中有一个roboto的字体库。字体的一些效果如下:
使用方式:
首先在assets目录下,新建一份fonts目录。将想要使用的字体文件(*.ttf)文件拷贝进来。
其次编写如下代码:
Typeface tf1 = Typeface.createFromAsset(getAssets(), "fonts/xxx.ttf"); TextView tv1 = new TextView(this); tv1.setTypeface(tf1); tv1.setText("0123"); tv1.setTextSize(20);
这里给出一个完整的实例:
xml文件定义:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/ll_root" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" android:typeface="normal" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" android:typeface="sans" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" android:typeface="serif" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" android:typeface="monospace" /> </LinearLayout>
java代码部分:
import android.app.Activity; import android.graphics.Typeface; import android.os.Bundle; import android.widget.LinearLayout; import android.widget.TextView; import com.example.androidtest.R; public class TypeFaceDemo extends Activity { private LinearLayout llRoot; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_typeface); llRoot = (LinearLayout) this.findViewById(R.id.ll_root); Typeface tf1 = Typeface.createFromAsset(getAssets(), "fonts/digitalfont.ttf"); TextView tv1 = new TextView(this); tv1.setTypeface(tf1); tv1.setText("数字时钟效果:0123"); tv1.setTextSize(20); Typeface tf2 = Typeface.createFromAsset(getAssets(), "fonts/bold.ttf"); TextView tv2 = new TextView(this); tv2.setTypeface(tf2); tv2.setText("abcde"); tv2.setTextSize(20); Typeface tf3 = Typeface.createFromAsset(getAssets(), "fonts/roboto_regular.ttf"); TextView tv3 = new TextView(this); tv3.setTypeface(tf3); tv3.setText("ABCD"); tv3.setTextSize(20); Typeface tf4 = Typeface.createFromAsset(getAssets(), "fonts/simkai.ttf"); TextView tv4 = new TextView(this); tv4.setTypeface(tf4); tv4.setText("上面的几种对只能针对英文字符,对中文不起作用。所以从xp系统中拷贝了楷体字体。不过xp系统的字体文件有3m左右大小"); tv4.setTextSize(20); llRoot.addView(tv1); llRoot.addView(tv2); llRoot.addView(tv3); llRoot.addView(tv4); } }
要注意的是:Android提供的roboto字体库只对英文起作用。
要注意的是:Android提供的roboto字体库只对英文起作用。