【Android】自定义控件系列之TextView设置Drawable的大小
16lz
2021-01-23
1.attr.xml
<?xml version="1.0" encoding="utf-8"?>
2.继承TextView重写方法
package com.leaves.customwidget;import android.content.Context;import android.content.res.TypedArray;import android.graphics.drawable.Drawable;import android.util.AttributeSet;import android.widget.TextView;/** * 自定义TextView * @author leaves * */public class DrawableTextView extends TextView {public DrawableTextView(Context context) {this(context, null);}public DrawableTextView(Context context, AttributeSet attrs) {this(context, attrs, 0);}public DrawableTextView(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);/** * 取得自定义属性值 */TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.DrawableTextView);int drawableWidth = ta.getDimensionPixelSize(R.styleable.DrawableTextView_drawableWidth, -1);int drawableHeight = ta.getDimensionPixelSize(R.styleable.DrawableTextView_drawableHeight, -1);/** * 取得TextView的Drawable(左上右下四个组成的数组值) */Drawable[] drawables = getCompoundDrawables();Drawable textDrawable = null;for (Drawable drawable : drawables) {if (drawable != null) {textDrawable = drawable;}}/** * 设置宽高 */if (textDrawable != null && drawableWidth != -1 && drawableHeight != -1) {textDrawable.setBounds(0, 0, drawableWidth, drawableHeight);}/** * 设置给TextView */setCompoundDrawables(drawables[0], drawables[1], drawables[2], drawables[3]);/** * 回收ta */ta.recycle();}}
3.使用
4.运行对比效果 更多相关文章
- Android中的HashMap原理实践探索,重写equals(),为什么重写hashCode
- Android定义字符串数组资源并在程序中使用
- Android中重写onBackPressed()方法实现双击退出
- 两种button点击后改变颜色的方法selectot和重写
- Android(Java):滑动删除实现——重写onTouch
- 关于用Android的API重写drawRegion方法的代码
- Android资源文件 - 使用资源存储字符串 颜色 尺寸 整型 布尔值
- android重写Dialog
- 重写Button实现图片drawableTop和文字一起居中