自定义View之设置字体和夜间白天模式的TextView
看了鸿洋大神的博客:http://blog.csdn.net/lmj623565791/article/details/24252901自己仿照也写一个自定义View
自定义View 的步骤
1、自定义View的属性
2、在View的构造方法中获得我们自定义的属性
[ 3、重写onMesure ]
4、重写onDraw
1、自定义View的属性,首先在res/values/ 下建立一个attrs.xml , 在里面定义我们的属性和声明我们的整个样式。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="FontTextView">
<attr name="typefaceName" format="string"></attr>
<attr name="themeMode" format="string"></attr>
</declare-styleable>
</resources>
自定义属性使用三个参数的构造方法:
//自定义属性使用的构造方法
public FontTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.mcontext = context;
TypedArray a = context.getTheme().obtainStyledAttributes(attrs,R.styleable.FontTextView,defStyleAttr,0);
int n = a.getIndexCount();
for(int i = 0; i < n; i++){
int attr = a.getIndex(i);
switch (attr){
case R.styleable.FontTextView_typefaceName:
typefaceName = a.getString(attr);
break;
case R.styleable.FontTextView_themeMode:
themeMode = a.getString(attr);
break;
}
}
setTypefaceName(typefaceName);
setThemeMode();
a.recycle();
}
//设置主题模式 夜间 白天模式 也可以自己去定义更多的模式
public void setThemeMode(){
if(themeMode.equals("night")){
this.setTextColor(Color.WHITE);
this.setBackgroundColor(Color.BLACK);
}else if(themeMode.equals("day")){
this.setTextColor(Color.BLACK);
this.setBackgroundColor(Color.WHITE);
}else if(themeMode.equals("") || (themeMode == null)){
}
}
//设置字体名称 这里注意 android studio 可能会报错 找不到字体 具体参考:
http://stackoverflow.com/questions/26986932/font-asset-not-found-helvetica-ttf-on-lollipop
https://code.google.com/p/android-developer-preview/issues/detail?id=608&thanks=608&ts=1404735239
把assets/fonts 文件夹放到main目录下 而不是res目录下 就可以消除错误了
public void setTypefaceName(String typefaceName){
this.typefaceName = typefaceName;
Typeface typeface = Typeface.createFromAsset(mcontext.getAssets(),"fonts/"+typefaceName+".ttf");
this.setTypeface(typeface);
System.gc();
}
注意另外两个构造方法默认也要调用自定义构造方法:
public FontTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public FontTextView(Context context) {
this(context, null);
}
//引用FontTextView
typefaceName 参数是放置在assets/fonts 文件夹下的字体文件名称
<com.gac.fonttextview.FontTextView android:text="这是一个可以自定义字体和自定义夜间白天主题的TextView" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
gac:themeMode="night"
gac:typefaceName="xxsjs"
/>
源码下载地址:https://github.com/gacmy/fonttextview