最近开始整理之前部分可能用到的代码,发现在android项目中图片的显示最开始是用src指定image地址,但是这样的弊端就是如果图片颜色需要修改就需要更换图片,后来就是导入svg文件转为xml,在xml中可以更换图标的颜色,这样实现了样式中图标颜色的动态UI,但是用了一段时间后发现,svg越来越多造成项目臃肿,不好管理,于是自定义一个view来实现功能
因为现在android很对开源的图标库也有很多,github上有一大片,但是因为自己的项目对应的图标毕竟冷门且偏僻,
所以推荐使用阿里图标库:https://www.iconfont.cn/ 这个库还是很全的
闲话少说上代码
1 首先自定义一个ImageView ,代码比较简单,继承TextView,如果有其他自定义的事件可以往里面增加
import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Typeface; import android.util.AttributeSet; import android.widget.TextView; /** * Created by admin on 2018/3/15. */ @SuppressLint("AppCompatCustomView") public class IconView extends TextView { /* * 控件在xml加载的时候是调用两个参数的构造函数 ,为了自定义的控件的完整性我们可以 * 都把构造函数写出来 */ public IconView(Context context) { super(context); init(context); } public IconView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public IconView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context); } /** * 初始化 * * @param context */ private void init(Context context) { //设置字体图标 Typeface font = Typeface.createFromAsset(context.getAssets(), "font/iconfont.ttf"); this.setTypeface(font); } }
2 上一步中自定义的VIEW中需要一个iconfont.ttf的文件,这个文件是字体样式文件,我放到了下面这个目录
3 获取ttf文件,如果你有现成的可以导入进去,我是登录阿里的图标库,新建一个项目
4 在图标库中搜素你需要的图标或者图片,增加到购物车并转存到你刚刚新的项目中,打开你的项目并下载文件到本地
5 文件下载到本地进行解压,复制iconfont.ttf当项目中去
6 在values新增icon_strings文件,并需要定义你的图片对应文件码
7 此时可以在资源文件中正式使用了,其中android:textSize 控制图标大小,android:textColor控制图标的颜色, android:text="@string/icon_home_person"就是icon_strings.xml中定义的字段
<com.test.uu.view.deftag.IconView android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center_vertical" android:text="@string/icon_home_person" android:textColor="@color/colorGreen" android:textSize="@dimen/font_size_title" />