网上查资料,都是用方法一(java代码中设置字体)实现的,但是findViewById 写的很烦。
如果TextView很多都需要设置字体的话,那要崩溃了。于是尝试采用方法二:自定义控件的办法实现
1、方法一:在java代码中设置字体
Button是TextView的子类,所以可以同样可以设置字体(TypeFace)
步骤:
1.1、xml中添加控件
1.2、java中设置字体
2、方法二:自定义控件
一般字体文件(.ttf)都是放在asset文件夹下,所以:
Application:记得要在 main.xml中配置
package com.example.test_font;
import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Typeface;
public class MyApplication extends Application {
public static Typeface mTf = null;
@Override
public void onCreate() {
System.out.println("@@ MyApplication onCreate");
mTf = Typeface.createFromAsset(this.getAssets(),"fonts/FZSEJW_4.TTF");
super.onCreate();
}
@Override
public void onTerminate() {
System.out.println(" @@ onTerminate");
super.onTerminate();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
System.out.println(" @@ onConfigurationChanged");
super.onConfigurationChanged(newConfig);
}
@Override
public void onLowMemory() {
System.out.println(" @@ onLowMemory");
super.onLowMemory();
}
@SuppressLint("NewApi")
@Override
public void onTrimMemory(int level) {
System.out.println(" @@ onTrimMemory");
super.onTrimMemory(level);
}
}
package com.example.test_font;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class MyTextView extends TextView {
//inflect xml 的时候,执行的这个构造器,xml中指定了控件MyTextView的参数(有Attribute的)
public MyTextView(Context context,AttributeSet att) {
super(context, att);
}
@Override
public void setTypeface(Typeface tf) {
super.setTypeface(MyApplication.mTf);
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/test_TV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="天才宝宝" />
<Button
android:id="@+id/test_BT"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="天才宝宝2" />
<com.example.test_font.MyTextView
android:id="@+id/test_MTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="天才宝宝3" />
</LinearLayout>
总结:
1、如果需要自定义Button的字体,那怎么实现呢?难道还要再写一个MyButton extends Button,然后重写设置字体的方法吗?
2、个人感觉,读取assert文件夹中的 ttf 文件,获取TypeFace类写的有点恶心,
哪位有更好的方法,求指教,求交流,求留言!