我正在尝试构建一个带有进度条的按钮,该进度条显示在按钮的中心,而不是文本,只要点击按钮,同时进行一些后台处理。我正在做的是有一个自定义按钮并将动画设置为按钮左侧的可绘制对象,并在 onDraw 中将动画移动到按钮的中心。但是,在点击按钮后的一小段时间内,我不知道为什么按钮上有2个进度条。
public class ButtonWithProgressBar extends Button {
protected int progressId = R.drawable.progress_bar;
protected Drawable progress;
protected CharSequence buttonText;
@Override
public void setText(CharSequence text, BufferType type) {
super.setText(text, type);
if (Strings.notEmpty(text)) {
buttonText = text;
}
}
public void startSpinning()
{
if(isSpinning()){
return;
}
progress = getContext().getResources().getDrawable(progressId);
final Drawable[] old = getCompoundDrawables();
setCompoundDrawablesWithIntrinsicBounds(old[0], old[1], progress, old[3]);
setEnabled(false);
if(progress instanceof Animatable){
((Animatable)progress).start();
}
setText("");
}
public void stopSpinning()
{
if(!isSpinning()){
return;
}
if(progress instanceof Animatable){
((Animatable)progress).stop();
}
setEnabled(true);
setText(buttonText);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (progress != null) {
final int drawableHeight = progress.getIntrinsicHeight();
final int drawableWidth = progress.getIntrinsicWidth();
final int drawableTop = (getHeight() - drawableHeight) / 2;
final int drawableLeft = (getWidth() - drawableWidth) / 2;
progress.setBounds(drawableLeft, drawableTop, drawableLeft + drawableWidth, drawableTop + drawableHeight);
progress.draw(canvas);
}
}
}
这会在点击后显示一小段时间,然后一切都看起来像我想要的那样:
任何想法为什么会发生这种情况?