Android 实现图片icon和TextView简易组合显示

     将图片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);
    }
}

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值