本文共 3142 字,大约阅读时间需要 10 分钟。
在开发过程中我们往往会遇到图片旁边带文字的布局,这种布局有些比较Low的开发会直接用一个ImageView和TextView,有经验的会给TextView设置DrawableLeft、DrawableRight等等属性,一个View搞定,但是这个属性设置图片是无法控制大小的,在xml里面,当然在Java代码里是可以设置的。
TextView textView = new TextView(mContext); Drawable drawable = getResources().getDrawable(R.drawable.icon_friend); // 设置图片的大小 drawable.setBounds(0, 0, 20, 20); // 设置图片的位置,左、上、右、下 textView.setCompoundDrawables(null, null, drawable, null);
当然,我们还可以用自定义View来实现这个效果,代码也是非常的简单
import android.content.Context;import android.content.res.TypedArray;import android.graphics.drawable.Drawable;import android.support.annotation.Nullable;import android.util.AttributeSet;import com.rzj.zhongshi.R;public class DrawableTextView extends android.support.v7.widget.AppCompatTextView { private Drawable drawableLeft = null, drawableTop = null, drawableRight = null, drawableBottom = null; private int drawableWidth, drawableHeight; public DrawableTextView(Context context) { this(context, null); } public DrawableTextView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public DrawableTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.DrawableTextView); int count = typedArray.getIndexCount(); for(int i = 0; i < count; i++){ int attr = typedArray.getIndex(i); switch (attr){ case R.styleable.DrawableTextView_drawableRight: drawableRight = typedArray.getDrawable(attr); break; case R.styleable.DrawableTextView_drawableLeft: drawableLeft = typedArray.getDrawable(attr); break; case R.styleable.DrawableTextView_drawableTop: drawableTop = typedArray.getDrawable(attr); break; case R.styleable.DrawableTextView_drawableBottom: drawableBottom = typedArray.getDrawable(attr); break; case R.styleable.DrawableTextView_drawableWidth: drawableWidth = typedArray.getDimensionPixelSize(attr, 0); break; case R.styleable.DrawableTextView_drawableHeight: drawableHeight = typedArray.getDimensionPixelSize(attr,0); break; } } if(null != drawableLeft){ drawableLeft.setBounds(0,0, drawableWidth, drawableHeight); } if(null != drawableRight){ drawableRight.setBounds(0,0, drawableWidth, drawableHeight); } if(null != drawableTop){ drawableTop.setBounds(0,0, drawableWidth, drawableHeight); } if(null != drawableBottom){ drawableBottom.setBounds(0,0, drawableWidth, drawableHeight); } setCompoundDrawables(drawableLeft, drawableTop, drawableRight, drawableBottom); }}
转载地址:http://aowlo.baihongyu.com/