如何在ImageSwitcher中使用Glide加载图片

3

为了创建图像幻灯片,我想使用带有计时器的图像切换器。我阅读了这篇博客文章,非常清晰,但它不会从网络加载图像。现在我想使用Glide库从网络加载图像。

这是MainActivity:

public class MainActivity extends Activity {
    private ImageSwitcher imageSwitcher;

    private int[] gallery = { http://www.helloworld.com/image1.png, http://www.helloworld.com/image2.png, http://www.helloworld.com/image3.png,
            http://www.helloworld.com/image4.png, };

    private int position;

    private static final Integer DURATION = 2500;

    private Timer timer = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageSwitcher = (ImageSwitcher) findViewById(R.id.imageSwitcher);
        imageSwitcher.setFactory(new ViewFactory() {

            public View makeView() {
                return new ImageView(MainActivity.this);
            }
        });

        // Set animations
        // https://danielme.com/2013/08/18/diseno-android-transiciones-entre-activities/
        Animation fadeIn = AnimationUtils.loadAnimation(this, R.anim.fade_in);
        Animation fadeOut = AnimationUtils.loadAnimation(this, R.anim.fade_out);
        imageSwitcher.setInAnimation(fadeIn);
        imageSwitcher.setOutAnimation(fadeOut);
    }

    // ////////////////////BUTTONS
    /**
     * starts or restarts the slider
     * 
     * @param button
     */
    public void start(View button) {
        if (timer != null) {
            timer.cancel();
        }
        position = 0;
        startSlider();
    }

    public void stop(View button) {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    public void startSlider() {
        timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {

            public void run() {
                // avoid exception:
                // "Only the original thread that created a view hierarchy can touch its views"
                runOnUiThread(new Runnable() {
                    public void run() {
                        imageSwitcher.setImageResource(gallery[position]);
                        position++;
                        if (position == gallery.length) {
                            position = 0;
                        }
                    }
                });
            }

        }, 0, DURATION);
    }

    // Stops the slider when the Activity is going into the background
    @Override
    protected void onPause() {
        super.onPause();
        if (timer != null) {
            timer.cancel();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (timer != null) {
            startSlider();
        }

    }

}

我尝试使用Glide加载图片,但我不知道该怎么做。
3个回答

6

这很容易做到,你只需要使用 Glide 将图片加载到从 ImageSwitcher 的方法 imageSwitcher.getCurrentView() 获取的 ImageView 中即可。因此,您需要将 runOnUiThread 方法中的代码替换为以下代码:

Glide.with(MainActivity.this)
    .load(gallery[position])
    .asBitmap()
    .listener(new RequestListener<String, Bitmap>() {
        @Override
        public boolean onException(Exception e, String model, Target<Bitmap> target, boolean isFirstResource) {
            return false;
        }

        @Override
        public boolean onResourceReady(Bitmap resource, String model, Target<Bitmap> target, boolean isFromMemoryCache, boolean isFirstResource) {
            position++;
            if (position == gallery.length) {
                position = 0;
            }
            imageSwitcher.setImageDrawable(new BitmapDrawable(getResources(), resource));
            return true;
        }
    }).into((ImageView) imageSwitcher.getCurrentView());

同样,别忘了用适当的链接替换你的图像链接(我看到你现在有一些虚拟链接)。因此,你的gallery数组应该是一个String[]数组。
同时不要忘记在AndroidManifest.xml中包含android.permission.INTERNET
最后,你需要在xml中将ImageSwitcherandroid:layout_width属性改为match_parent,否则Glide无法在其中加载图片。

1
我认为批准的答案很棒,但是它缺少一些关键内容。当他们更新当前图片时,这基本上只是替换了视图中的图片。这意味着我们最好根本不使用ImageSwitcher。我们需要做的是更新下一个视图,然后显示它。这将使我们能够看到我们添加的任何过渡效果。
我已经在自己的代码中将所有这些逻辑分离出来,以使其更加清晰,但这里是原始形式。
设置您的ImageSwitcher
   

    Animation in = AnimationUtils.loadAnimation(this,android.R.anim.fade_in);
       Animation out = AnimationUtils.loadAnimation(this,android.R.anim.fade_out);
       imageSwitcher.setFactory(() -> {
                ImageView imageView = new ImageView(getApplicationContext());
                imageView.setLayoutParams(new FrameLayout.LayoutParams(
                        FrameLayout.LayoutParams.MATCH_PARENT,
                        FrameLayout.LayoutParams.MATCH_PARENT
                ));
                return imageView;
            });
       imageSwitcher.setInAnimation(in);
       imageSwitcher.setOutAnimation(out);

  


调用此函数以更新下一张图片。
   

    RequestOptions requestOptions = new 
       RequestOptions().diskCacheStrategy(DiskCacheStrategy.ALL);
       Bitmap nextImage = getAppropriateImage();
       GlideApp.with(this)
          .load(nextImage)
          .apply(requestOptions)
          .into((ImageView) imageSwitcher.getNextView());
       imageSwitcher.showNext();


改进此答案的两个评论: 1)在“下一个”图像加载完成之前不要调用showNext()。 2)像下面的回复建议的那样将“下一个”视图设置为INVISIBLE。 - jpage4500
@jpage4500,您能分享一下您的解决方案吗? - Tara

0
我使用了@rom4ek的版本,但出现了一些崩溃:
``` Fatal Exception: java.lang.RuntimeException Canvas: trying to use a recycled bitmap android.graphics.Bitmap@7ad49c4 ```
我认为这是因为drawable未设置到传递给into(...)的同一个ImageView中。
我将其更改为使用“下一个视图”。我们必须将Glide的可见性从GONE更改为INVISIBLE。
imageSwitcher.getNextView().setVisibility(View.INVISIBLE);
Glide.with(...)
    .load(url)
    .listener(new RequestListener<String, Bitmap>() {
        @Override
        public boolean onException(Exception e, String model, Target<Drawable> target, boolean isFirstResource) {
            return false;
        }

        @Override
        public boolean onResourceReady(Drawable resource, String model, Target<Drawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
            imageSwitcher.setImageDrawable(resource);
            return true;
        }
    }).into((ImageView) imageSwitcher.getNextView());

Kotlin版本:

it.nextView.visibility = View.INVISIBLE
Glide.with(...)
    .load(url)
    .listener(object : RequestListener<Drawable> {
        override fun onLoadFailed(
            e: GlideException?,
            model: Any?,
            target: Target<Drawable>?,
            isFirstResource: Boolean
        ): Boolean {
            return false
        }

        override fun onResourceReady(
            resource: Drawable?,
            model: Any?,
            target: Target<Drawable>?,
            dataSource: DataSource?,
            isFirstResource: Boolean
        ): Boolean {
            it.setImageDrawable(resource)
            return true
        }
    })
    .into(it.nextView as ImageView)

我已将其更改为使用“下一个视图”。我们必须将Glide的可见性从GONE设置为INVISIBLE。这对我有用,因为最初我在Glide将图像加载到“下一个”视图时遇到了问题。我怀疑这是因为该视图不可见,而Glide只是跳过它。 - jpage4500

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接