Android 让自定义TextView的drawableLeft与文本一起居中
前言
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 uses-permission权限列表中文注释版
Android有一个精心设计的安全模型。每一个应用都有其自己Linux用户和群组,在单独的进程和VM上运行,不能影响到其他应用2014-05-05Fragment通过FragmentManager实现通信功能详细讲解
这篇文章主要介绍了Fragment通过FragmentManager实现通信功能,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习吧2023-01-01解决android报错:Intel HAXM is required to run this AVD
这篇文章主要介绍了解决android报错:Intel HAXM is required to run this AVD,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-11-11android中SwipeRefresh实现各种上拉,下拉刷新示例
这篇文章主要介绍了android中SwipeRefresh实现各种上拉,下拉刷新示例,非常具有实用价值,需要的朋友可以参考下。2017-03-03
最新评论