字体图标库在网页中广泛应用,同样可以用在安卓上,优点就是无论在任何尺寸下,可缩放的矢量图形都会为您呈现出完美的图标。例如阿里的iconFoint库和Font Awesome的矢量图标,是我们常常用到的库。下面我们就在android 中自定义使用图标字体来替代ImageView。
步骤也很简单:
1. 下载字体库,例如fontawesome.ttf。放到android 项目中的assets目录下。也可以自己做一个图标字体库。
2. 在String.xml定义好图标对应的unicode编码(如下图)
3. 自定义TextView,代码很简单:
public class IconFontTextView extends TextView{
public IconFontTextView(Context context) {
super(context);
init(context);
}
public IconFontTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
/***
* 设置字体
*
* @return
*/
public void init(Context context) {
Typeface tf = Typeface.createFromAsset(context.getAssets(), "fontawesome.ttf");
setTypeface(tf);
}
在使用的时候:
<com.UI.IconFontTextView
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="right"
android:text="@string/angle_right"/>