代码动态设置图标的大小和位置的工具类

来源:互联网 发布:公共基础知识考试软件 编辑:程序博客网 时间:2024/05/02 04:48


项目中经常需要实现一个界面中n个这种item,一开始我的实现方法是:LinearLayout包含,左边ImageView,中间TextView,右边ImageView。

布局优点:ImageView可直接设置大小。

布局缺点:绘制过度,控件数量多,xml代码行数多。

项目开发没那么紧张后,我开始重构代码,优化这个布局,我改用了TextView+drawableLeft+drawableRight的方式,实现了同样的效果。

布局优点:xml代码行数减少,简洁明了。

布局缺点:GPU绘制的值没什么变化,依然绘制过度,图标大小无法在xml中设置,只能代码设置。


我发现图标+文字的布局很常见,而图标的位置在文字的上下左右都有可能。于是我写了个工具类,可以代码动态设置图标的大小和位置。与大家分享,有什么不对和需要改进的地方也希望大家不吝指正。

/** * 代码设置图片尺寸和位置 * @author zhanghui * @date 2016-10-11 16:52 */public class DrawableSizeUtils {/** * 代码设置drawableLeft/drawableRight/drawableTop/drawableBottom图片尺寸 * (未指定宽高,用默认的宽高值) * @param mContext * @param view * @param resid * @param position 1:left;2:top;3:right;4:bottom */public static void setDrawableSize(Context mContext, Button view, int resid, int position) {Drawable drawable = mContext.getResources().getDrawable(resid);// / 这一步必须要做,否则不会显示.drawable.setBounds(0, 0, mContext.getResources().getDimensionPixelSize(R.dimen.x22),mContext.getResources().getDimensionPixelSize(R.dimen.x22));switch (position) {case Constant.POSITION_LEFT:// 左view.setCompoundDrawables(drawable, null, null, null);break;case Constant.POSITION_TOP:// 上view.setCompoundDrawables(null, drawable, null, null);break;case Constant.POSITION_RIGHT:// 右view.setCompoundDrawables(null, null, drawable, null);break;case Constant.POSITION_BOTTOM:// 下view.setCompoundDrawables(null, null, null, drawable);break;default:break;}}/** * 代码设置drawableLeft/drawableRight/drawableTop/drawableBottom图片尺寸 * @param mContext * @param view * @param resid * @param position1:left;2:top;3:right;4:bottom * @param width * @param height */public static void setDrawableSize(Context mContext, Button view, int resid, int position,int width, int height) {Drawable drawable = mContext.getResources().getDrawable(resid);// / 这一步必须要做,否则不会显示.drawable.setBounds(0, 0, width, height);switch (position) {case Constant.POSITION_LEFT:// 左view.setCompoundDrawables(drawable, null, null, null);break;case Constant.POSITION_TOP:// 上view.setCompoundDrawables(null, drawable, null, null);break;case Constant.POSITION_RIGHT:// 右view.setCompoundDrawables(null, null, drawable, null);break;case Constant.POSITION_BOTTOM:// 下view.setCompoundDrawables(null, null, null, drawable);break;default:break;}}/** * 代码设置左边图片的尺寸,右边图片默认为箭头 * (未指定位置,用默认的位置值) * @param mContext * @param view * @param resid * @param width * @param height */public static void setDrawableSize(Context mContext, Button view, int resid, int width, int height) {Drawable drawableLeft = mContext.getResources().getDrawable(resid);Drawable drawableRight = mContext.getResources().getDrawable(R.drawable.arrow_right);// 这一步必须要做,否则不会显示.drawableLeft.setBounds(0, 0, width, height);drawableRight.setBounds(0, 0, drawableRight.getMinimumWidth(),drawableRight.getMinimumHeight());view.setCompoundDrawables(drawableLeft, null, drawableRight, null);}}

当然,这个工具类还是有局限的地方,只适用于给Button控件(RadioButton也可以)设置一个方向的图标。两个图标的话,右边默认是箭头,无法进行个性化定制。


0 0
原创粉丝点击