将图片ICON放在TextView的头部、中间、尾部等,可以用Html或自定义实现。
1.方法一:
代码如下:
mTvContent.setText(Html.fromHtml(descString(), getImageGetterInstance(), null)); private String descString() { return "爱从来都不会缺席,只是需要耐心地等待而已 " + "<img src='" + R.mipmap.icon_foot + "'/>"; } public Html.ImageGetter getImageGetterInstance() { Html.ImageGetter imgGetter = new Html.ImageGetter() { @Override public Drawable getDrawable(String source) { int id = Integer.parseInt(source); Drawable d = getResources().getDrawable(id); int wdp = dip2px(UIUtils.getContext(), 20); int hdp = dip2px(UIUtils.getContext(), 20); d.setBounds(0, 0, wdp, hdp); return d; } }; return imgGetter; } public static int dip2px(Context context, float dpValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); }2.方法二:
TextView mTextView = new TextView(getContext()); mTextView.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.picture1), null,null,null);//依次是左、上、右、下,有就是位置,没有就是null mTextView.setCompoundDrawablePadding(30);//设置文字与图标间距更好的实现居中显示效果:
public class VoiceBoxView extends FrameLayout { TextView text; public VoiceBoxView(Context context){ super(context); setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); setBackgroundResource(R.drawable.voice_box_bg); setPadding(0,9,0,0);//将上面的宽度加入layout的padding,下面的textView就可以居中啦 text = new TextView(context); text.setSingleLine(true); text.setTextSize(24); text.setTextColor(getResources().getColor(R.color.c_1)); text.setText("语音呼出 “请帮我开启洗衣机的什模式” "); text.getPaint().setFakeBoldText(true); text.setGravity(Gravity.CENTER_VERTICAL); text.setPadding(0,8,0,8);//保证图片的上下间距 text.setCompoundDrawablePadding(10); text.setCompoundDrawablesWithIntrinsicBounds(null, null,getResources().getDrawable(R.drawable.voice_box_icons),null); FrameLayout.LayoutParams textLayoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); textLayoutParams.leftMargin = 24; textLayoutParams.rightMargin = 8; textLayoutParams.gravity = Gravity.CENTER_VERTICAL; text.setSingleLine(true); addView(text, textLayoutParams); } }
