简体   繁体   中英

Show random images in imageview from assest folder in xml

I want to add images from asses to an imageview automatically. the below code does work well when images are in a drawable folder, but I want to create a separate folder name avatar in the asset folder and get random images from there in my imageview.

int[] images = new int[] {R.drawable.image01, R.drawable.image02, R.drawable.image03};

// Get the ImageView
setContent(R.layout.main);
ImageView mImageView = (ImageView)findViewById(R.id.myImageView);

// Get a random between 0 and images.length-1
int imageId = (int)(Math.random() * images.length);

// Set the image
mImageView.setBackgroundResource(images[imageId]);

Thanks in advance.

I suggest you to use AssetManager.list() To list all the assets for the given folder within /assets folder, we use AssetManager.list() . Suppose we have some files within /assets/img and we need to list all those files, then we write code as follows.

String[] imgPath = assetManager.list("img"); Here we get String array of file names within img directory. 在此处输入图像描述

try {
            String[] imgPath = assetManager.list("img");
            for (int i = 0; i< imgPath.length; i++) {
                InputStream is = assetManager.open("img/"+imgPath[i]);
                Log.d(TAG, imgPath[i]);
                Bitmap  bitmap = BitmapFactory.decodeStream(is);
                
                imageViewbyCode = new ImageView(this);
                imageViewbyCode.setImageBitmap(bitmap);
                LinearLayout.LayoutParams params =  new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                imageViewbyCode.setLayoutParams(params);        
                myLayout.addView(imageViewbyCode);
            }
         } catch (IOException e) {
            Log.e(TAG, e.getMessage());
         }

Please try below code:-

 AssetManager assetManager = getAssets();
   ImageView mImageView = (ImageView)findViewById(R.id.myImageView);
   InputStream inputStream = assetManager.open("yourimage.jpg")
    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
    mImageView.setImageBitmap(bitmap);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM