为TextView
创建自定义视图。
在attrs.xml
文件中添加条目,并在自定义TextView
中提供选择字体的选项列表。
创建一个枚举条目,其中包含字体列表并分配唯一值。
在strings.xml
中记录所有字体的条目:
Roboto-Bold
Roboto-Medium
Roboto-Light
Roboto-Regular
Roboto-Thin
Roboto-Italic
创建一个资源文件夹并将所有要放入字体文件夹中的必要字体复制到该文件夹中。
创建一个继承TextView
的类。
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class CustomFontTextView extends TextView {
String customFont;
public CustomFontTextView(Context context, AttributeSet attrs) {
super(context, attrs);
style(context, attrs);
}
public CustomFontTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
style(context, attrs);
}
private void style(Context context, AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.CustomFontTextView);
int cf = a.getInteger(R.styleable.CustomFontTextView_fontName, 0);
int fontName = 0;
switch (cf)
{
case 1:
fontName = R.string.Roboto_Bold;
break;
case 2:
fontName = R.string.Roboto_Italic;
break;
case 3:
fontName = R.string.Roboto_Light;
break;
case 4:
fontName = R.string.Roboto_Medium;
break;
case 5:
fontName = R.string.Roboto_Regular;
break;
case 6:
fontName = R.string.Roboto_Thin;
break;
default:
fontName = R.string.Roboto_Regular;
break;
}
customFont = getResources().getString(fontName);
Typeface tf = Typeface.createFromAsset(context.getAssets(),
"font/" + customFont + ".ttf");
setTypeface(tf);
a.recycle();
}
}
您可以这样使用此自定义类。..使用您的packageName.ClassName
<ankit.com.customui.CustomFontTextView
android:layout_width="match_parent"
android:text="Hello World Ankit"
android:textSize="16sp"
app:fontName="Roboto_Medium"
android:layout_height="wrap_content"/>
在res/values/attrs.xml文件中添加以下可样式化内容:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomFontTextView">
<attr name="fontName" format="string" />
</declare-styleable>
</resources>