如何获取自定义TextView的自定义字体名称属性以设置字体到TextView中。
根据属性值在TextView中设置字体。
public class MyTextView extends TextView
{
public MyTextView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
init();
}
public MyTextView(Context context, AttributeSet attrs)
{
super(context, attrs);
init();
}
public MyTextView(Context context)
{
super(context);
init();
}
public void init()
{
// set font_name based on attribute value of textview in xml file
String font_name = "";
if (!isInEditMode())
{
Typeface tf = Typeface.createFromAsset(getContext().getAssets(),
"fonts/"+font_name);
setTypeface(tf);
}
}
在Xml文件中
<com.Example.MyTextView
android:id="@+id/header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
fontname="font.ttf"
android:text="Header"
/>
我也将font.ttf文件放在assets->fonts中 谢谢