【Android】自定义控件系列之TextView设置Drawable的大小
16lz
2022-01-27
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 贪吃蛇源码分析
- android 设置搜狗输入法为默认输入法
- Android(安卓)初步学习BroadCast与Service实现简单的音乐播放器
- Android(安卓)Studio 3.3.2运行OSChina4.1.7
- Android(安卓)app开机启动
- Android(安卓)PopupWindow做的分享界面
- android之ArrayAdaper之Spinner
- IllegalStateException,PatternSyntaxException,Android(安卓)stud
- android连接服务器下载文件工具类