我有一个我想强调的ImageButton - 例如。下载完成后闪烁。
我正在尝试将背景设置为TransitionDrawable
并在转换完成后重置它,但我得到了奇怪的结果:
这是我用来激活转换,反转它并恢复原始可绘制背景的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 drawable的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>
答案 0 :(得分:2)
通过在将背景设置为转换后手动设置填充来解决 - 我不得不使用xml中为按钮设置的填充值的两倍。
例如。
downloadButton.setBackgroundResource(R.drawable.animate_background);
downloadButton.setPadding(28, 28, 28, 28);