使用TransitionDrawable渐变切换多张图片,供大家参考,具体内容如下
1、定义变量
private int change = 0;//记录下标
private int[] ids = new int[]{R.drawable.anim_one, R.drawable.anim_two, R.drawable.anim_three};
private Drawable[] drawables;//图片集合
private Thread mThread;//线程
private boolean mThreadFlag = true;//线程结束标志符
2、填充图片
private void initDrawableView() {
//填充图片
drawables = new Drawable[ids.length];
for (int i = 0; i < ids.length; i++) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
drawables[i] = getDrawable(ids[i]);
} else {
drawables[i] = getResources().getDrawable(ids[i]);
}
}
}
3、定义hander
private Handler mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
int duration = msg.arg1;
TransitionDrawable transitionDrawable = new TransitionDrawable(new Drawable[]{drawables[change % ids.length],
drawables[(change + 1) % ids.length]});
change++;//改变标识位置
repeatPlay.setBackground(transitionDrawable);
transitionDrawable.startTransition(duration);
return false;
}
});
4、开启线程发送消息,让transition一直在改变
private class MyRunnable implements Runnable {
@Override
public void run() {
//这个while(true)是做死循环
while (mThreadFlag) {
int duration = 5000;//改变的间隔
Message message = mHandler.obtainMessage();
message.arg1 = duration;
mHandler.sendMessage(message);
try {
Thread.sleep(duration);
//隔duration秒发送一次
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
5、在onCreate()中开启线程,改变transition,切换图片
mThread = new Thread(new MyRunnable());
mThread.start();
6、在onDestroy()中结束线程
mThreadFlag = false;//结束线程
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持得得之家。
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!