Search code examples
androidandroid-glideanimated-gifpostdelayed

PostDelayed and Handler not working and run with no delay


I have a list of animated gifs in drawable resource folder in my android project. I need these gifs played one by one, wait for seconds, and then play the next gif. but when I run the app, all gifs load very very fast so I can just see the last gif. I used Glide for playing gifs and this is my code

Handler handler1 = new Handler();        

for (int a = 1; a<=lines.size() ;a++) {
    handler1.postDelayed(new Runnable() {

        @Override
        public void run() {
            String resName = "";
            int duration = 0;
            resName = "wo_" + (lines.get(slideIndex).split(",")[0]).toLowerCase().trim().replace(".gif", "");
            duration = Integer.parseInt(lines.get(slideIndex++).split(",")[2].trim());
            int resourceId = getResId(resName, R.drawable.class);//this.getResources().getIdentifier(resName, "drawable", this.getPackageName());

            Glide.with(WorkoutActivity.this).asGif().load(resourceId).into(imageView);
        }
    }, 5000);
}

Solution

  • You can use Timer for this

       // Declare globally
    private int position = -1;
    
    /**
     * This timer will call each of the seconds.
     */
    Timer mTimer = new Timer();
    mTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            // As timer is not a Main/UI thread need to do all UI task on runOnUiThread
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                        // increase your position so new image will show
                    position++;
                    // check whether position increased to length then set it to 0
                    // so it will show images in circuler
                    if (position >= imageArray.length)
                        position = 0;
                    // Set Image
                    MyImageView.setImageResource(imageArray[position]);
                }
            });
        }
    }, 0, 5000);