2014-02-10 48 views
0

我有一个ImageButton,我想突出显示 - 例如。下载完成后闪烁。转换为ImageButton背景

我想要的背景设置为TransitionDrawable和重置回当过渡完成,但我得到怪异的结果:

  • 按钮的填充消失,一旦过渡激活和ISN恢复原始绘图时,恢复原状。
  • 过渡仅发生在按钮的笔触(边框)上,而不是填充背景区域的渐变。

这是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> 

动画开始XML(动画端很相似,只是不同的颜色梯度和中风)

<?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> 

回答

2

解决由后手动设置填充设置背景转换 - 我不得不使用两次在xml中为按钮设置的填充值。

例如。

downloadButton.setBackgroundResource(R.drawable.animate_background); 
downloadButton.setPadding(28, 28, 28, 28);