Android TransitionDrawable:过渡动画Drawable
Android TransitionDrawable实现一种可以用动画表示的Drawable。写一个例子。
package zhangphil.app; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.TransitionDrawable; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.ImageView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //定义一个过渡drawable数组,最后一个drawable:drawables[n-1]是最终的显示形式 //第一个是开始 Drawable[] drawables=new Drawable[]{new ColorDrawable(Color.TRANSPARENT),new ColorDrawable(Color.RED)}; TransitionDrawable td=new TransitionDrawable(drawables); ImageView image = (ImageView) findViewById(R.id.imageView); image.setImageDrawable(td); //交叉淡入样式 td.setCrossFadeEnabled(true); //开始执行动画,从设定的时间内,缓慢的从TransitionDrawable构造时候的数组第一个drawable(drawables[0])渐变成最后数组最后一个drawable(drawables[n-1]) //动画执行结束后,最终显示的是最后一个drawables[n-1] td.startTransition(500); } }
如果要用xml实现TransitionDrawable,需要在drawable目录下新建一个xml代码文件,比如transition.xml,代码:
<?xml version="1.0" encoding="utf-8"?> <transition xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@android:color/transparent" /> <item android:drawable="@android:color/holo_red_dark"/> </transition>
上层Java代码变成:
TransitionDrawable transition = (TransitionDrawable)getResources().getDrawable(R.drawable.transition); ImageView image = (ImageView) findViewById(R.id.imageView); image.setImageDrawable(transition); transition.setCrossFadeEnabled(true); transition.startTransition(500);