Android自定义TextView实现drawableLeft内容居中

Android自定义TextView实现drawableLeft内容居中,第1张

概述如何实现使用TextView的DrawableLeft使图片和文字居中显示呢???代码如下:1.首先自定义一个类,继承TextView

如何实现使用TextVIEw的Drawableleft使图片和文字居中显示呢???

代码如下:

1.首先自定义一个类,继承TextVIEw

package com.test.signcalendar.weight;import androID.content.Context;import androID.graphics.Canvas;import androID.graphics.drawable.Drawable;import androID.util.AttributeSet;import androID.Widget.TextVIEw;/** * 自定义TextVIEw,实现drawableleft可以和文字一起居中 * @author HLQ * @createtime 2016年3月20日04:14:36 * */public class DrawableCenterTextVIEw extends TextVIEw {  public DrawableCenterTextVIEw(Context context,AttributeSet attrs,int defStyle) {    super(context,attrs,defStyle);  }  public DrawableCenterTextVIEw(Context context,AttributeSet attrs) {    super(context,attrs);  }  public DrawableCenterTextVIEw(Context context) {    super(context);  }  @OverrIDe  protected voID onDraw(Canvas canvas) {    Drawable[] drawables = getCompoundDrawables();    if (drawables != null) {      Drawable drawableleft = drawables[0];      if (drawableleft != null) {        float textWIDth = getPaint().measureText(getText().toString());        int drawablepadding = getCompoundDrawablepadding();        int drawableWIDth = 0;        drawableWIDth = drawableleft.getIntrinsicWIDth();        float bodyWIDth = textWIDth + drawableWIDth + drawablepadding;        canvas.translate((getWIDth() - bodyWIDth) / 2,0);      }    }    super.onDraw(canvas);  }}

2.之后在xml布局文件中直接引用即可。。。

<com.test.signcalendar.weight.DrawableCenterTextVIEw          androID:ID="@+ID/textVIEw1111"          androID:layout_wIDth="0dp"          androID:layout_height="wrap_content"          androID:layout_weight="1"          androID:drawableleft="@drawable/fmhp_mine_health_plan_signcalendar_finish_status_bg"          androID:drawablepadding="5dp"//给图片和文字之间设置填充          androID:text="都完成"          androID:textcolor="#333333"          androID:textSize="12sp" />

3。ok实现效果 如下。。。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

总结

以上是内存溢出为你收集整理的Android自定义TextView实现drawableLeft内容居中全部内容,希望文章能够帮你解决Android自定义TextView实现drawableLeft内容居中所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1145946.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-31
下一篇2022-05-31

发表评论

登录后才能评论

评论列表(0条)

    保存