屏幕快照 2016-07-24 12.26.07.png
最后经过仔细排查发现是由别的组成员自定义view造成的,这个自定义view代码如下:
RightDrawableButton.java
public class RightDrawableButton extends Button {
....
@Override
protected void onDraw(Canvas canvas) {
Drawable[] drawables = getCompoundDrawables();
if (drawables != null) {
Drawable drawableLeft = drawables[2];
if (drawableLeft != null) {
float textWidth = getPaint().measureText(getText().toString());
int drawablePadding = getCompoundDrawablePadding();
int drawableWidth = 0;
drawableWidth = drawableLeft.getIntrinsicWidth();
float bodyWidth = textWidth + drawableWidth + drawablePadding;
setPadding(0, 0, (int)(getWidth() - bodyWidth), 0);
canvas.translate((getWidth() - bodyWidth) / 2, 0);
}
}
super.onDraw(canvas);
}
}
相信看完代码大家应该知道代码想要实现的效果了:
让button的文本和drawableRight居中对齐。
实现的效果如下图:
有些朋友可能会认为:实现这个效果直接用button和drawableRight在XML中定义不就可以了么?大家可以自己试试哟
核心思想:
canvas.translate((getWidth() - bodyWidth) / 2, 0);
OK,最终效果是实现了,可是效率有极大的问题。问题就出在getCompoundDrawables()
这行代码中,进入源码发现其实现为:
@NonNull
public Drawable[] getCompoundDrawables() {
final Drawables dr = mDrawables;
if (dr != null) {
return dr.mShowing.clone();
} else {
return new Drawable[] { null, null, null, null };
}
}
很明显,此方法要不创建新的Drawable数组,要不就clone() mDrawables数组。无论是克隆还是新建都将创建新的数组,这里虽然Java使用浅拷贝来拷贝数组,但是数组本身会重新创建(只是数组成员引用被拷贝的数组成员)。
onDraw方法中由于使用了setPadding而导致button会调用invalide()来进行重绘,这就导致了onDraw在不断的被调用。
大家可以想想,作者为什么将这些代码放到onDraw中执行:我想是为了如果button的文本发生变化时需要重新计算bodyWidth的缘故
经过上面的分析,我们可以进行优化如下:
1,不要在onDraw中调用getCompoundDrawables,毕竟在运行过程中修改drawable的需求不多
2,计算bodyWidth放在onLayout中进行
最终代码实现如下:
public class RightDrawableButton extends Button {
private final static String TAG = "RightDrawableButton";
private Drawable[] drawables;
private float textWidth;
private float bodyWidth;
public RightDrawableButton(Context context) {
super(context);
init();
}
public RightDrawableButton(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public RightDrawableButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init(){
drawables = getCompoundDrawables();
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
textWidth = getPaint().measureText(getText().toString());
Drawable drawableRight = drawables[2];
int totalWidth = getWidth();
if (drawableRight != null) {
int drawableWidth = drawableRight.getIntrinsicWidth();
int drawablePadding = getCompoundDrawablePadding();
bodyWidth = textWidth + drawableWidth + drawablePadding;
setPadding(0,0,(int)(totalWidth - bodyWidth),0);
}
}
public void setText(String text){
if(text.equals(getText().toString()))
return;
super.setText(text);
requestLayout();
}
@Override
protected void onDraw(Canvas canvas) {
int width = getWidth();
canvas.translate((width - bodyWidth) / 2, 0);
super.onDraw(canvas);
}
}
得到运行结果如下(世界清静了):
如果你的代码是直接从网上扒的,请一定做好测试。
将问题提早暴露比后来再优化代码更加重要,如果个人能力有限请和同事们沟通解决方案,问题一定不能无限拖延下去(迟早要还的)
单就“让button的文本和drawableRight居中对齐”的问题其实完全有很多其它方法可以做到,不用非自己定义button来实现,比如:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/darker_gray"
android:gravity="center_horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:text="Button"
android:drawableRight="@android:drawable/ic_delete"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="50dp"
android:background="@android:color/darker_gray"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:id="@+id/id_text"
android:text="textView"
android:drawableRight="@android:drawable/ic_delete"/>
</RelativeLayout>
LGDrawableButton.java
//在构造函数中调用
private void init(Context context, AttributeSet attrs) {
if (attrs != null) {
TypedArray a = context.getTheme().obtainStyledAttributes(
attrs, R.styleable.LGDrawableButton, 0, 0);
try {
//textMarginRight:文本和drawableRight之间的距离
textMarginRight = a.getDimension(R.styleable.LGDrawableButton_textMarginRight, 0);
//textMarginLeft:文本和drawableLeft之间的距离
textMarginLeft = a.getDimension(R.styleable.LGDrawableButton_textMarginLeft, 0);
setDrawable(a.getDrawable(R.styleable.LGDrawableButton_drawableLeft),
a.getDrawable(R.styleable.LGDrawableButton_drawableRight));
} finally {
a.recycle();
}
}
pl = getPaddingLeft();
pr = getPaddingRight();
}
@Override
//计算button的size
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = 0;
int height = 0;
if (mDrawableRight != null) {
width += mDrawableRight.getIntrinsicWidth();
height = mDrawableRight.getIntrinsicHeight();
}
if (mDrawableLeft != null) {
width += mDrawableLeft.getIntrinsicWidth();
int drawableLeftHeight = mDrawableLeft.getIntrinsicHeight();
height = height > drawableLeftHeight ? height : drawableLeftHeight;
}
setMeasuredDimension(Math.max(getMeasuredWidth(), width), Math.max(getMeasuredHeight(), height));
}
@Override
//更新文本的padding值
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (mDrawableRight != null) {
textPaddingRight = mDrawableRight.getIntrinsicWidth() / 2;
}
if (mDrawableLeft != null) {
textPaddingLeft = mDrawableLeft.getIntrinsicWidth() / 2;
}
if (mDrawableLeft != null && mDrawableRight != null) {
textPaddingRight = 0;
textPaddingLeft = 0;
}
setPadding(pl + textPaddingLeft * 2 + (int)textMarginLeft / 2, getPaddingTop(),
pr + textPaddingRight * 2 + (int)textMarginRight / 2, getPaddingBottom());
}
public void setDrawable(final Drawable left, final Drawable right) {
int[] state;
state = getDrawableState();
if (left != null) {
left.setState(state);
//设置drawable的绘图坐标为drawable图片左上角(方便定位drawable的位置)
left.setBounds(0, 0, left.getIntrinsicWidth(), left.getIntrinsicHeight());
left.setCallback(this);
}
if (right != null) {
...
}
mDrawableRight = right;
mDrawableLeft = left;
requestLayout();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mDrawableRight != null) {
//更新mDrawableRight的x坐标
Rect rect = mDrawableRight.getBounds();
float textWidth = getPaint().measureText(getText().toString());
float drawableX = getWidth() / 2 + textWidth / 2 - textPaddingRight + textMarginRight / 2;
if (drawableX + rect.width() >= getWidth()) {
drawableX = getWidth() - rect.width();
}
canvas.save();
canvas.translate(drawableX, getHeight() / 2 - rect.bottom / 2);
mDrawableRight.draw(canvas);
canvas.restore();
}
if (mDrawableLeft != null) {
...和mDrawableRight类似
}
}
由于涉及到自定义属性,请在res的values目录下新建attrs.xml文件内容如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="LGDrawableButton">
<attr name="drawableRight" format="reference"/>
<attr name="drawableLeft" format="reference"/>
<attr name="textMarginRight" format="dimension"/>
<attr name="textMarginLeft" format="dimension"/>
</declare-styleable>
</resources>
使用方法
在布局文件中定义如下:
<com.gui.lgdrawablebutton.LGDrawableButton
android:id="@+id/center_left"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:textMarginLeft="20dp"
android:text="中国你好"
app:drawableLeft="@android:drawable/ic_delete" />
<com.gui.lgdrawablebutton.LGDrawableButton
android:id="@+id/center_right"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="中国你好"
app:textMarginRight="20dp"
app:drawableRight="@android:drawable/ic_delete" />
<com.gui.lgdrawablebutton.LGDrawableButton
android:id="@+id/center_both"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="中国你好"
app:drawableRight="@android:drawable/ic_delete"
app:drawableLeft="@mipmap/ic_launcher"/>
实现效果如下:
尽量不要做个“拿来主义”的人,我个人认为网上的一些代码不是不能使用,只是我们要有自己的衡量:这些代码是不是能直接使用,还是说经过简单修改就能直接使用,还是根本就不能用。请做个有自己想法的“拿来主义”者,能显著提高你的工作效率。