控制不同的文字字体
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)); }}