我们在很多时候 我们在做程序的时候 需要把我们程序中的某些文字更改一下字体以满足我们自己程序的需要 但是我们知道 在android系统中 他仅仅只支持那么几个字体 而且有些还是对中文没效果 那么我们在写自己的程序的时候怎么来达到这一目的呢 其实很简单
有一点遗憾的是 在android程序 在布局文件的xml中 不能直接实现字体的转换 我们只能在代码里面实现
首先我们将我们需要的字体 放在assets/fonts里面 注意的是 字体的命名要是英文字母起的名
先抛开代码不说 我们平时用word的时候 也有这样的情况 就是当你用到某一个字体的时候 有些中文是没有效果的 只有相对应的 英文会有效果 在我们的程序中 也是这样的情况 有些字体是不支持中文的 就是说当有中文和英文混在一起的时候 使用某种字体 会只有英文的字体改变了 至于那些字体是只对英文的字体改变有效果 这个我就不多说了 应该都知道
先截个图 这是我的字体存放位置和字体文件的命名
xml 的文件内容是这样的
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
android:textSize="30dip" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
android:textSize="30dip" />
<TextView
android:id="@+id/text1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
android:textSize="30dip" />
<TextView
android:id="@+id/text2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
android:textSize="30dip" />
</LinearLayout>
在 java代码中 我们需要添加的代码主要就是这样的一句
TextView tv = (TextView) findViewById(com.fu.R.id.textview);
Typeface face = Typeface.createFromAsset(getAssets(), "fonts/shaonv.ttf");
tv.setTypeface(face);
对于这个程序来讲 我们需要添加的是这样的 只是对这个代码的重复
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.textview);
Typeface face = Typeface.createFromAsset(getAssets(), "fonts/shaonv.ttf");
tv.setTypeface(face);
TextView tv1 = (TextView) findViewById(R.id.text1);
Typeface face1 = Typeface.createFromAsset(getAssets(), "fonts/wawaziti.ttf");
tv1.setTypeface(face1);
TextView tv2 = (TextView) findViewById(R.id.text2);
Typeface face2 = Typeface.createFromAsset(getAssets(), "fonts/Enoksen.ttf");
tv2.setTypeface(face2);
}
}
效果图