我创建了一个自定义 TextView 来使用 Font Awesome 支持,当您
在布局 xml 中添加文本(unicode)时它工作正常。但是,如果我尝试使用 动态设置来自我的适配器的文本view.setText()
,则它不会应用字体。
字体视图类
public class FontView extends TextView {
private static final String TAG = FontView.class.getSimpleName();
//Cache the font load status to improve performance
private static Typeface font;
public FontView(Context context) {
super(context);
setFont(context);
}
public FontView(Context context, AttributeSet attrs) {
super(context, attrs);
setFont(context);
}
public FontView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setFont(context);
}
private void setFont(Context context) {
// prevent exception in Android Studio / ADT interface builder
if (this.isInEditMode()) {
return;
}
//Check for font is already loaded
if(font == null) {
try {
font = Typeface.createFromAsset(context.getAssets(), "fontawesome-webfont.ttf");
Log.d(TAG, "Font awesome loaded");
} catch (RuntimeException e) {
Log.e(TAG, "Font awesome not loaded");
}
}
//Finally set the font
setTypeface(font);
}
}
用于布局的 XML
<com.domain.app.FontView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="60sp"
android:textAlignment="center"
android:text=""
android:gravity="center"
android:id="@+id/iconView"
android:background="@drawable/oval"
android:padding="10dp"
android:layout_margin="10dp" />
我的适配器
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
IconListHolder viewHolder;
if( convertView == null ) {
LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = layoutInflater.inflate(R.layout.icon, null);
viewHolder = new IconListHolder(v);
v.setTag(viewHolder);
} else {
viewHolder = (IconListHolder) v.getTag();
}
//Set the text and Icon
viewHolder.textViewIcon.setText(pages.get(position).getIcon());
viewHolder.textViewName.setText(pages.get(position).getTitle());
return v;
}
private class IconListHolder {
public FontView textViewIcon;
public TextView textViewName;
public IconListHolder(View base) {
textViewIcon = (FontView) base.findViewById(R.id.iconView);
textViewName = (TextView) base.findViewById(R.id.iconTextView);
}
}
请帮助我做错了什么。