学习自:http://blog.csdn.net/u014702653/article/details/52304656
非常简单,但是特别实用
values/attrs
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="DrawableTextView"> <attr name="drawable_src" format="reference"/> <attr name="drawable_height" format="dimension"/> <attr name="drawable_width" format="dimension"/> <attr name="drawable_location"> <enum name="left" value="1"/> <enum name="top" value="2"/> <enum name="right" value="3"/> <enum name="bottom" value="4"/> </attr> </declare-styleable> </resources>
自定义的view
public class DrawableTextView extends android.support.v7.widget.AppCompatTextView { public DrawableTextView(Context context) { super(context); } public DrawableTextView(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } public DrawableTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } //设置方向 private static final int LEFT = 1, TOP = 2, RIGHT = 3, BOTTOM = 4; //从attrs中获取期望的drawable的宽高,资源,上下左右4个位置 private void init(AttributeSet attrs) { if (attrs != null) { TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.DrawableTextView); int mWidth = a.getDimensionPixelSize (R.styleable.DrawableTextView_drawable_width, 0); int mHeight =a.getDimensionPixelSize (R.styleable.DrawableTextView_drawable_height,0); Drawable mDrawable =a.getDrawable (R.styleable.DrawableTextView_drawable_src); int mLocation = a.getInt (R.styleable.DrawableTextView_drawable_location, LEFT); a.recycle(); drawDrawable(mDrawable, mWidth, mHeight, mLocation); } } private void drawDrawable(Drawable mDrawable, int mWidth, int mHeight, int mLocation) { if (mDrawable != null) { if (mWidth != 0 && mHeight != 0) { mDrawable.setBounds(0, 0, mWidth, mHeight); } switch (mLocation) { case LEFT: this.setCompoundDrawables(mDrawable, null, null, null); break; case TOP: this.setCompoundDrawables(null, mDrawable, null, null); break; case RIGHT: this.setCompoundDrawables(null, null, mDrawable, null); break; case BOTTOM: this.setCompoundDrawables(null, null, null, mDrawable); break; } } } }
使用
<com.example.onebuyapp.DrawableTextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/price" android:textSize="11sp" android:drawablePadding="6dp" android:gravity="center" android:textColor="@color/black_51" android:layout_marginStart="30dp" app:drawable_src="@drawable/sort_from_bottom_to_top_or_top_to_bottom" app:drawable_height="9dp" app:drawable_width="6dp" app:drawable_location="right" tools:ignore="SmallSp" />
效果