如何使用毕加索随机加载图像

时间:2018-08-07 11:33:39

标签: java android android-imageview picasso

我想知道是否有可能使用毕加索从数组中加载随机挑选的图像?

这是我用来加载专辑封面的代码,但是我想要实现的是,当找不到专辑封面时,我想显示随机图像而不是同一张图像。

private void loadAlbumArt(){

    Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
    Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri, songList.get(songIndex).getAlbumID());

    Picasso.with(getApplicationContext())
            .load(albumArtUri)
            .placeholder(R.drawable.no_album)
            .error(R.drawable.no_album)
            .noFade()
            .resize(500, 0)
            .into(mAlbumArt);

}

预先感谢

文斯

3 个答案:

答案 0 :(得分:1)

尝试一下:

int[] myImageList = new int[]{R.drawable.img1, R.drawable.img2, R.drawable.img3,
            R.drawable.img4, R.drawable.img5, R.drawable.img6};

    Random random = new Random();
    int randomNumber = random.nextInt(myImageList.length);

    Picasso.with(getApplicationContext())
            .load(albumArtUri)
            .placeholder(R.drawable.no_album)
            .error(myImageList[randomNumber])
            .noFade()
            .resize(500, 0)
            .into(mAlbumArt);

答案 1 :(得分:0)

您可以输入此代码

检查专辑封面是否可用,因此方法如下

 private void loadAlbumArt() {

        Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
        Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri, songList.get(songIndex).getAlbumID());
        if (!albumArtUri.equalsIgnoreCase("")) {
            Picasso.with(getApplicationContext())
                    .load(albumArtUri)
                    .noFade()
                    .resize(500, 0)
                    .into(mAlbumArt);
        } else {
            int[] myImageList = new int[]{R.drawable.img1, R.drawable.img2, R.drawable.img3,
                    R.drawable.img4, R.drawable.img5, R.drawable.img6};

            Random random = new Random();
            int randomNumber = random.nextInt(myImageList.length);

            Picasso.with(getApplicationContext())
                    .load(myImageList[randomNumber])
                    .noFade()
                    .resize(500, 0)
                    .into(mAlbumArt);
        }
    }

现在,当专辑封面不可用时,您可以显示随机图像

答案 2 :(得分:0)

private void loadAlbumArt(){

    Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
    Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri, songList.get(new Random().nextInt(songList.size())).getAlbumID());

    Picasso.with(getApplicationContext())
            .load(albumArtUri)
            .placeholder(R.drawable.no_album)
            .error(R.drawable.no_album)
            .noFade()
            .resize(500, 0)
            .into(mAlbumArt);

}