我需要为listview项目添加自定义字体。我已经使用这样的适配器将值添加到列表中
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), newList, R.layout.club_list2, from, to);
在这里,我想在club_list2布局中为textviews设置字体。这怎么可能?
如果要从xml设置自定义字体,可以执行此操作
public class TypefaceTextView extends TextView {
private static Map<String, Typeface> mTypefaces;
public TypefaceTextView(final Context context) {
this(context, null);
}
public TypefaceTextView(final Context context, final AttributeSet attrs) {
this(context, attrs, 0);
}
public TypefaceTextView(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
if (mTypefaces == null) {
mTypefaces = new HashMap<String, Typeface>();
}
// prevent exception in Android Studio / ADT interface builder
if (this.isInEditMode()) {
return;
}
final TypedArray array = context.obtainStyledAttributes(attrs, styleable.TypefaceTextView);
if (array != null) {
final String typefaceAssetPath = array.getString(
R.styleable.TypefaceTextView_customTypeface);
if (typefaceAssetPath != null) {
Typeface typeface = null;
if (mTypefaces.containsKey(typefaceAssetPath)) {
typeface = mTypefaces.get(typefaceAssetPath);
} else {
AssetManager assets = context.getAssets();
typeface = Typeface.createFromAsset(assets, typefaceAssetPath);
mTypefaces.put(typefaceAssetPath, typeface);
}
setTypeface(typeface);
}
array.recycle();
}
}
}
在xml中。
<com.example.TypefaceTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textSize="30sp"
android:text="@string/hello_world"
geekui:customTypeface="fonts/yourfont.ttf" />
并且您的字体应位于asset / fonts /文件夹中
在值内创建资源文件并将其设置为名称attrs.xml
然后复制过去
<resources>
<declare-styleable name="TypefaceTextView">
<attr name="customTypeface" format="string" />
</declare-styleable>
</resources>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句