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.运行对比效果



更多相关文章

  1. android 贪吃蛇源码分析
  2. android 设置搜狗输入法为默认输入法
  3. Android(安卓)初步学习BroadCast与Service实现简单的音乐播放器
  4. Android(安卓)Studio 3.3.2运行OSChina4.1.7
  5. Android(安卓)app开机启动
  6. Android(安卓)PopupWindow做的分享界面
  7. android之ArrayAdaper之Spinner
  8. IllegalStateException,PatternSyntaxException,Android(安卓)stud
  9. android连接服务器下载文件工具类

随机推荐

  1. 安装Android sdk 4.4(19)出现问题的解决
  2. Android仿微信图片选择器(三)
  3. Android:EditText 多行显示及所有属性(不自
  4. Android 中的消息传递,详解广播机制
  5. Android分发机制
  6. android中编译资源文件的相关问题
  7. Android Intent 教程
  8. Android NDK 环境搭建
  9. 17.Android与JavaScript相互调用
  10. Android发展演变与开发环境搭建