iis服务器助手广告广告
返回顶部
首页 > 资讯 > 移动开发 >Android 让自定义TextView的drawableLeft与文本一起居中
  • 691
分享到

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

居中Android 2022-06-06 08:06:37 691人浏览 安东尼
摘要

前言   TextView的drawableLeft、drawableRight和drawableTop是一个常用、好用的属性,可以在文本的上下左右放置一个图片,而不

前言

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

正文

 一、效果图

 二、实现代码

 自定义控件



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 DrawableTextView图片文字居中显示实例Android自定义TextView实现drawableLeft内容居中Android自定义TextView实现文字图片居中显示的方法


--结束END--

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

本文链接: https://www.lsjlt.com/news/24562.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作