欢迎来到代码驿站!

Android代码

当前位置:首页 > 移动开发 > Android代码

Android 让自定义TextView的drawableLeft与文本一起居中

时间:2021-05-19 09:40:46|栏目:Android代码|点击:

前言

  TextView的drawableLeft、drawableRight和drawableTop是一个常用、好用的属性,可以在文本的上下左右放置一个图片,而不使用更加复杂布局就能达到,我也常常喜欢用RadioButton的这几个属性实现很多效果,但是苦于不支持让drawbleLeft与文本一起居中,设置gravity为center也无济于事,终于有空研究了一下,这里与大家一起分享。

正文

 一、效果图

 二、实现代码

 自定义控件

/**
 * drawableLeft与文本一起居中显示
 * 
 * 
 */
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);
 }
}

总结:和普通TextView用法一致,无需额外增加属性,drawableRight不能用。

以上就是对自定义控件让TextView的drawableLeft与文本一起居中显示的问题解决,需要的朋友可以参考下。

上一篇:Android ViewPager相册横向移动的实现方法

栏    目:Android代码

下一篇:Android实现带附件的邮件发送功能

本文标题:Android 让自定义TextView的drawableLeft与文本一起居中

本文地址:http://www.codeinn.net/misctech/124439.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有