首先你需要定義這個類。
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