项目刚接触到Icon Font,用字体文件取代图片,对于个人开发者或者缺少UI的项目,无疑是雪中送炭,下面是我在Android开发中使用Icon Font遇到的问题及解决方法做一个记录,同时希望能够帮助可能有需要的大家。
操作步骤
首先去http://www.iconfont.cn/plus/collections/index图标库选择自己要用的图标下载,下载后得到个压缩文件并解压,最后得到如下文件:
其中2个文档可以不要,将剩余的文件拷贝到项目的assets目录下:
然后打开demo.html来找到图标相对应的 HTML 实体字符码:
然后在string定义需要用到的图标字符码:
<string name="str_code"></string>
<string name="str_zan"></string>
<string name="str_see"></string>
最后定义TextView实现:
<TextView
android:id="@+id/textview_code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/str_code" />
import android.graphics.Typeface;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Typeface iconfont = Typeface.createFromAsset(getAssets(), "iconfont/iconfont.ttf");
TextView textview = (TextView)findViewById(R.id.like);
textview.setTypeface(iconfont);
}
以上步骤来自:http://www.iconfont.cn/help/iconuse.html,我也是根据上面的步骤学习的(ps:只不过我这里的比他详细)。
问题
上面的使用方法只是IconFont的基本使用,如果是配置在项目里面的死图标基本可以满足需求,多定义几个string就可以了,但是我项目里是服务器返回动态生成的图标,所以我不可以把字符码定义到string.xml里面需要代码添加:
Typeface iconfont = Typeface.createFromAsset(getAssets(), "iconfont/iconfont.ttf");
registerNow = (TextView)findViewById(R.id.register_now);
registerNow.setText("");
registerNow.setTypeface(iconfont);
这里问题就来了,他不显示图标,显示的& #xe71c;字符串,而我如果通过getString方法它又能正常显示图标:
Typeface iconfont = Typeface.createFromAsset(getAssets(), "iconfont/iconfont.ttf");
registerNow = (TextView)findViewById(R.id.register_now);
registerNow.setText(getResources().getString(R.string.str_code));
registerNow.setTypeface(iconfont);
按照以往的经验,这应该跟 unicode 字符有关,
http://www.iconfont.cn/help/iconuse.html里面也有介绍:
最后把前面的”&#x” 替换成 “\u”,用 unicode 字符来表示,
Typeface iconfont = Typeface.createFromAsset(getAssets(), "iconfont/iconfont.ttf");
registerNow = (TextView)findViewById(R.id.register_now);
registerNow.setText("\ue71c");
registerNow.setTypeface(iconfont);
这样问题就解决了,可以正常显示!