天天看點

控制不同的文字字型

TextView對象中有許多與字形相關的方法,使用setTextSize方法來改變字型大小,用setTypeface方法來指定使用字型等等。

如果你想使用内部預設的Typeface,用defaultFromStyle()方法即可。但是,如果你想要通過外部的資源來構造Typeface,步驟如下:

1. 事先在assets目錄下建立一個fonts檔案夾

2. 放入要使用的字型檔案(.ttf)

3. 提供相對路徑給createFromAsset()來建立Typeface對象

使用外部Typeface如下:

eg.

textview.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/HandmadeTypewriter.ttf"));
           

使用内部Typeface,如下:

website.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
           

完整代碼:

package com.kevin.textview;

import android.app.Activity;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.TextView;

public class TextViewActivity extends Activity {
	private TextView website, email, phone;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        website = (TextView) findViewById(R.id.tv_website);
        email = (TextView)findViewById(R.id.tv_email);
        phone = (TextView) findViewById(R.id.tv_phone);
        // 設定文本值
        website.setText(R.string.website);
        email.setText(R.string.email);
        phone.setText(R.string.phone);

        // 設定字型大小
        website.setTextSize(20);
        // 設定字型
        /*
         * 使用内部預設的Typeface,用defaultFromStyle()方法
         * 如果你想要通過外部的資源來構造Typeface,步驟如下:
         * 1. 事先在assets目錄下建立一個fonts檔案夾
         * 2. 放入要使用的字型檔案(.ttf)
         * 3. 提供相對路徑給createFromAsset()來建立Typeface對象
         */
           website.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));        
    }
}