我有一个我想突出显示的 ImageButton - 例如。下载完成后闪烁。
我正在尝试将背景设置为 aTransitionDrawable
并在转换完成时将其重置,但我得到了奇怪的结果:
- 一旦激活过渡,按钮的填充就会消失,并且在完成后恢复原始可绘制对象时不会恢复。
- 过渡只发生在按钮的笔触(边框)上,而不是填充背景区域的渐变。
这是我用来激活转换、反转转换并恢复原始可绘制背景的 Java 代码:
downloadButton.setBackgroundResource(R.drawable.animate_background);
Drawable background = downloadButton.getBackground().getCurrent();
if (background instanceof TransitionDrawable) {
TransitionDrawable transition = (TransitionDrawable) background;
transition.startTransition(300);
downloadButton.postDelayed(new Runnable() {
@Override
public void run() {
// reverse the transition after it completes
Drawable background = downloadButton.getBackground().getCurrent();
if (background instanceof TransitionDrawable) {
TransitionDrawable transition = (TransitionDrawable) background;
transition.reverseTransition(200);
downloadButton.postDelayed(new Runnable() {
@Override
public void run() {
// restore original background
downloadButton.setBackgroundResource(R.drawable.custom_button);
}
}, 200); // after reverse transition
}
}
}, 300); // after transition
}
这是布局 xml 中的按钮:
<ImageButton
android:id="@id/download_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/custom_button"
android:padding="14dp"
android:src="@drawable/download_icon" />
这是 custom_button 可绘制的 xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" >
<shape>
<solid android:color="#343434" />
<stroke android:width="1dp" android:color="#171737" />
<corners android:radius="5dp" />
</shape>
</item>
<item>
<shape>
<gradient android:startColor="#343434" android:endColor="#171737" android:angle="270" />
<stroke android:width="1dp" android:color="#171717" />
<corners android:radius="5dp" />
</shape>
</item>
过渡“animate_background”xml:
<?xml version="1.0" encoding="UTF-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/animate_start" />
<item android:drawable="@drawable/animate_end" />
</transition>
Animate start xml(animate end 非常相似,只是渐变和描边的颜色不同)
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<gradient android:startColor="#34F434" android:endColor="#174717" android:angle="270" />
<stroke android:width="2dp" android:color="#17F717" />
<corners android:radius="5dp" />
</shape>