1、自定義控件
https://github.com/hongyangAndroid/MixtureTextView
原理:MixtureTextView extends RelativeLayout,將圖片(包括gif)放在MixtureTextView中,根據屬性,例如alignParentRight等,在onLayout里獲取屬性值,在dispatchDraw里根據圖片所占的位置繪制文字,以此實現圖文混排
不足:圖片位置需要相對文字固定
2、使用html的img標簽實現
/** * 拼接圖片 * * @return */ private String descString(String s) { return s + "<img src='" + R.drawable.icon + "'/>"; }
tv_title.setText(Html.fromHtml(descString(bean.title), getImageGetterInstance(), null));
/** * ImageGetter用於text圖文混排 * * @return */ public Html.ImageGetter getImageGetterInstance() { Html.ImageGetter imgGetter = new Html.ImageGetter() { @Override public Drawable getDrawable(String source) { int fontH = (int) (getResources().getDimension(R.dimen.fontH)); int id = Integer.parseInt(source); Drawable d = getResources().getDrawable(id); int width = (int) ((float) d.getIntrinsicWidth() / (float) d.getIntrinsicHeight()) * fontH; d.setBounds(0, 0, width, fontH); return d; } }; return imgGetter; }
優點:簡單,易使用
不足:圖片位置適配不好處理(通過html標簽應該可以解決)
3、使用字體包ttf
原理:將圖案做在ttf里
string.xml,由設計給具體code
<string name="fa_dot_circle_o"></string> <string name="fa_wheelchair"></string> <string name="fa_vimeo_square"> </string> <string name="fa_try"></string> <string name="fa_plus_square_o"></string>
<string name="fa_dot_circle_o"></string>
<string name="fa_wheelchair"></string>
<string name="fa_vimeo_square"> </string>
<string name="fa_try"></string>
<string name="fa_plus_square_o"></string>
textView直接引用
Typeface font = Typeface.createFromAsset(getAssets(), "fontawesome-webfont.ttf"); tab1.setTypeface(font);
空格需要使用轉義字符
public static String blankSpace = "<font color=\"" + 0xff0000 + "\">  </font>"; public static String blankSpace2 = "<font color=\"" + 0xff0000 + "\">&emsp&emsp</font>";
優點:十分簡單
不足:圖片顏色只能設置單一色