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】自定义控件系列之TextView设置Drawable的大小_第1张图片


更多相关文章

  1. Android中的HashMap原理实践探索,重写equals(),为什么重写hashCode
  2. Android定义字符串数组资源并在程序中使用
  3. Android中重写onBackPressed()方法实现双击退出
  4. 两种button点击后改变颜色的方法selectot和重写
  5. Android(Java):滑动删除实现——重写onTouch
  6. 关于用Android的API重写drawRegion方法的代码
  7. Android资源文件 - 使用资源存储字符串 颜色 尺寸 整型 布尔值
  8. android重写Dialog
  9. 重写Button实现图片drawableTop和文字一起居中

随机推荐

  1. Android(安卓)一个apk多个ICON执行入口
  2. Android BroadcastReceiver
  3. Android display架构分析(七-2)
  4. 利用Android两行代码真正杀死你的App
  5. 【可能有点用的记录】Android Studio 3.2
  6. GET Android 摸拟器 IP.
  7. Android(安卓)界面—UI开发控件
  8. Android 复习笔记之图解TextView类及其XM
  9. 2月收藏
  10. [Android Pro] 注册 Google Play 开发者