如何在Android中,對TextView設置自己喜歡的字體呢?
下面介紹 2 種方法:
1、代碼中動態設置:
<!-- 這裏沒有設定字體,將在Java代碼中設定-->
<TextView Android:id="@+id/custom"
Android:text="Hello,World"
Android:textSize="20sp" />
① 在Android中引入其他字體,首先要將字體文件保存在assets/fonts/目錄下(字體格式.ttf)
②//得到TextView控件對象
TextView textView =(TextView)findViewById(R.id.custom);
③//將字體文件保存在assets/fonts/目錄下,創建Typeface對象
Typeface typeFace =Typeface.createFromAsset(getAssets(),"fonts/HandmadeTypewriter.ttf");
④//使用字體
textView.setTypeface(typeFace);
2、自定義TextView設置:
①建立MyApplication的類,用來設置字體
import android.app.Application;
import android.graphics.Typeface;
public class MyApplication extends Application {
private Typeface typeface;
private static MyApplication instance;
@Override
public void onCreate() {
super.onCreate();
instance = (MyApplication) getApplicationContext();
typeface = Typeface.createFromAsset(instance.getAssets(), "fonts/zfkt.TTF");//下載的字體
}
public static MyApplication getInstace() {
return instance;
}
public Typeface getTypeface() {
return typeface;
}
public void setTypeface(Typeface typeface) {
this.typeface = typeface;
}
}
②在AndroidManifest清單中初始化MyApplication
<application
android:name=".MyApplication.MyApplication" //初始化 MyApplication
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme"
tools:replace="android:icon">
③建立MyTextView
public class MyTextView extends TextView {
public MyTextView(Context context) {
super(context);
//設置字體
setTypeface(MyApplication.getInstace().getTypeface());
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
//設置字體
setTypeface(MyApplication.getInstace().getTypeface());
}
public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
//設置字體
setTypeface(MyApplication.getInstace().getTypeface());
}
}
④準備好之後直接Xml中使用
<com.ahbcd.app.fctms.utils.MyTextView
android:layout_width="@dimen/dp_60"
android:layout_height="@dimen/dp_60"
android:text="顯示字體" />
總結:
1、第一種可以改變字體,但是不適合大範圍使用,會出現視圖展現卡頓現象
2、適合大範圍使用,只是比第一種複雜
3、第一種適合一些靜態展現,不需要經常刷新界面的地方,動態展示推薦第二種方案,比如Adapter佈局當中