自定义控件让TextView的drawableLeft与文本一起居中显示
来源:互联网 发布:mac好玩的小游戏 编辑:程序博客网 时间:2024/06/05 05:31
前言
TextView的drawableLeft、drawableRight和drawableTop是一个常用、好用的属性,可以在文本的上下左右放置一个图片,而不使用更加复杂布局就能达到,我也常常喜欢用RadioButton的这几个属性实现很多效果,但是苦于不支持让drawbleLeft与文本一起居中,设置gravity为center也无济于事,终于有空研究了一下,这里与大家一起分享。
正文
一、效果图
二、实现代码
自定义控件
/** * drawableLeft与文本一起居中显示 * * @author 农民伯伯 * @see http://www.cnblogs.com/over140/p/3464348.html * */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不管用!
<com.example.zza_android_test4.DrawableCenterTextView android:id="@+id/text" android:layout_width="match_parent" android:layout_height="50dp" android:drawableLeft="@drawable/ic_launcher" android:gravity="center_vertical" android:text="@string/hello_world" />
转载:http://www.cnblogs.com/over140/p/3464348.html
0 0
- 【Android】自定义控件让TextView的drawableLeft与文本一起居中显示
- 自定义控件让TextView、Button的drawableLeft和drawableRight与文本一起居中显示
- 自定义控件让TextView的drawableLeft与文本一起居中显示
- 【Android】自定义控件让TextView的drawableLeft与文本一起居中显示
- 自定义控件让TextView的drawableLeft与文本一起居中显示
- 自定义控件让TextView的drawableLeft与文本一起居中显示
- 【Android】自定义控件让TextView的drawableLeft与文本一起居中显示
- 【Android】自定义控件让TextView的drawableLeft与文本一起居中显示
- 自定义控件让TextView的drawableLeft与文本一起居中显示
- 自定义控件让TextView(Radiobutton)、Button的drawableLeft和drawableRight与文本一起居中显示
- 自定义控件让TextView的drawableLeft与文本一起居中显示
- 自定义控件让TextView的drawableLeft与文本一起居中显示
- 【Android】自定义控件让TextView的drawableLeft与文本一起居中显示
- 自定义控件让EditText的drawableLeft与文本一起居中显示
- 让TextView的drawableLeft与文本一起居中
- TextView的drawableLeft与文本一起居中显示(以及代码设置drawableLeft)
- TextView、Button的drawableLeft和drawableRight与文本一起居中显示
- drawableleft与文本一起居中显示
- iOS10适配—注册推送错误:Code=3000
- 原生js获取当前li元素的索引及demo
- C++开源程序库评话
- JAVA如何把一个float四舍五入到小数点后2位,4位,或者其它指定位数
- 如何用css 绘制边长相等且有边框的六边形
- 自定义控件让TextView的drawableLeft与文本一起居中显示
- C#中 ()=>的含义
- Entity Framework 5.0系列之Code First数据库迁移
- LCM cmd&vdo模式 点翻转和列翻转区别
- 解决Android 5.0以上版本Button自带阴影效果的方法
- 2016-11-11 个人第一页博客
- Cookie与Session的区别
- CDN
- 小黄鸡(小贱鸡)机器人