首先你需要定义这个类。
public class CustomFontTextView extends AppCompatTextView {
private static final String CUSTOM_FONT = "cfont";
private static final String FONT_PATH = "fonts/";
private String ttfName;
private Typeface font;
private CharSequence text;
private BufferType type;
public CustomFontTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public CustomFontTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
this.ttfName = attrs.getAttributeValue(AppConstants.NAMESPACE, CUSTOM_FONT);
if (ttfName.startsWith("@string/") || ttfName.startsWith("@")) {
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CustomFontTextView);
this.ttfName = ta.getString(R.styleable.CustomFontTextView_cfont);
ta.recycle();
}
this.setPaintFlags(this.getPaintFlags() | Paint.SUBPIXEL_TEXT_FLAG);
try {
font = Typeface.createFromAsset(context.getAssets(), FONT_PATH + ttfName);
setTypeface(font);
} catch (Exception e) {
e.printStackTrace();
font = Typeface.defaultFromStyle(Typeface.NORMAL);
setTypeface(font);
}
setText(text, type);
}
@Override
public void setText(CharSequence text, BufferType type) {
try {
this.text = text;
this.type = type;
if (font == null)
return;
CustomFontStyling customFontStyling = new CustomFontStyling(getContext(), font);
super.setText(customFontStyling.getCustomText(text.toString()), type);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
后,您需要添加设置样式在attrs.xml
<declare-styleable name="CustomFontTextView">
<attr name="cfont" format="string" />
</declare-styleable>
终于在你的XML布局
<YOURAPPPACKAGE.CustomFontTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cfont="@string/open_sans_regular" />
你想从你的java代码创建一个新的'CustomTextView'对象?或xml布局? – pskink
在developer.android.com上有自定义视图的完整指南请参阅https://developer.android.com/training/custom-views/index.html – Fusselchen
拥有这种构造方法意味着可以使用此从'xml'布局定制视图,没有直接的方式通过java代码动态创建。 – azizbekian