Android Use TransitionDrawable Gradient to Switch Multiple Pictures

  • 2021-10-15 11:27:41
  • OfStack

Use TransitionDrawable gradient to switch multiple pictures for your reference, the specific contents are as follows

1. Define variables


private int change = 0;// Record subscript 
private int[] ids = new int[]{R.drawable.anim_one, R.drawable.anim_two, R.drawable.anim_three};
private Drawable[] drawables;// Picture collection 
private Thread mThread;// Thread 
private boolean mThreadFlag = true;// Thread end identifier 

2. Fill in the picture


private void initDrawableView() {
    // Fill in a picture 
    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. Define 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++;// Change the location of the logo 
      repeatPlay.setBackground(transitionDrawable);
      transitionDrawable.startTransition(duration);
      return false;
    }
  });

4. Open the thread to send messages, so that transition1 can be changed directly


private class MyRunnable implements Runnable {
    @Override
    public void run() {
      // This while(true) Is to do an infinite loop 
      while (mThreadFlag) {
        int duration = 5000;// The interval of change 
        Message message = mHandler.obtainMessage();
        message.arg1 = duration;
        mHandler.sendMessage(message);
        try {
          Thread.sleep(duration);
          // Septum duration Send in seconds 1 Times 
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }
  }

5. Open the thread in onCreate (), change transition, and switch pictures


mThread = new Thread(new MyRunnable());
mThread.start();

6. End the thread in onDestroy ()


mThreadFlag = false;// End thread 

Related articles: