Android version:4.2
I am developing an android App. I need to generate images from drawable folder randomly. In my drawable I have 45 images with different names.
My xml code is:
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
I have tried with this code:
ImageView img=(ImageView)findViewById(R.id.imageView1);
Random rand = new Random();
int rndInt = rand.nextInt(52) + 1;
String drawableName = "photo"+ rndInt;
int resID = getResources().getIdentifier(drawableName, "drawable", getPackageName());
img.setImageResource(resID);
But with this code I need to change my image names to photo1, photo2, ... and I don't want to do it.
Any suggestion on how to implement it? Thank you.
One way is to create an array with required image's ids. And take random one from that array. That approach is explained in other answers.
Another way is to create file random_images_array.xml in values folder of your project and fill it like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<array name="apptour">
<item>#drawable/image_1</item>
<item>#drawable/photo_2</item>
<item>#drawable/picture_4</item>
</array>
</resources>
And then you can take random image from that xml array:
final TypedArray imgs = getResources().obtainTypedArray(R.array.random_images_array);
final Random rand = new Random();
final int rndInt = rand.nextInt(imgs.length());
final int resID = imgs.getResourceId(rndInt, 0);
Third method is to take random field from R.drawable class:
final Class drawableClass = R.drawable.class;
final Field[] fields = drawableClass.getFields();
final Random rand = new Random();
int rndInt = rand.nextInt(fields.length);
try {
int resID = fields[rndInt].getInt(drawableClass);
img.setImageResource(resID);
} catch (Exception e) {
e.printStackTrace();
}
How about
long[] res = {R.drawable.image1, R.drawable.image2};
or
int[] res = {R.drawable.image1, R.drawable.image2};
and
int rndInt = rand.nextInt(res .length);
img.setImageDrawable(getResources().getDrawable(res[rndInt]));
Be specific about your question - what do you actually want to do?
if you want to show images in random order than this would be best
int resId[]={R.drawable.p1,R.drawable.p2,R.drawable.p2};
Random rand = new Random();
int index = rand.nextInt((resId.length- 1) - 0 + 1) + 0;
imgView.setImageResource(resId[index]);
If you want the absolute file path of image to rename it, see this article for details.
ImageView img=(ImageView)findViewById(R.id.imageView1);
String[] imageArray = {"Image1", "Image2", etc..};
Random rand = new Random();
int rndInt = rand.nextInt(52) + 1;
int resID = getResources().getIdentifier(imageArray[rand], "drawable", getPackageName());
img.setImageResource(resID);
You have to see this question or answer also:-
Randomize string from resources android
but you have to replace
textview.setText()
to
img.setImageResource(ran.nextInt(trivias.length)]);`
I found that setting an array with all of the drawables and then getting a random index through a random number would work.
public int[] Images = {R.drawable.1, R.drawable.2, R.drawable.3};
And then
ImageView EightBallImage = findViewById(R.id.EightBallImage);
EightBallImage.setImageResource(Images[new Random().nextInt(Images.length)]);
Either inside a click listener or just in the onCreate method
Related
I have raw folder with audio files from a.mp3 to z.mp3.
I would like to play them programatically.
int[ ] myMusic = {R.raw.(edittext.getText(first letter),R.raw.(edittext.getText(2nd letter)
How do I make it loop for all my files?
If I understand correctly...
// Get from a Context, such as Activity
Resources r = getResources();
String pkg = getPackageName();
// Extract and loops over text
String letters = edittext.getText().toString();
int size = letters.length();
int[] myMusic = new int[size];
for (int i = 0; i < size; i++) {
// Get the R.raw.letter values
int resId = r.getIdentifier(letters.charAt(i), "raw", pkg);
myMusic[i] = resId;
}
I think you want to play music on whatever String you have typed into your EditText. Every character represents a file name in raw folder. So, you will have to use every characeter of EditText as a file name.
int size = edittext.getText().toString().length();
int[] myMusic = new int[size ];
for(int i=0 ; i < size ; i++){
int resID=getResources().getIdentifier(edittext.getText().toString().substring(i,i), "raw", getPackageName());
myMusic[i] = resID;
}
I'm circulating some drawable images (fx. I have a few images named image_1, image_2 etc.) as header images in a fragment. The images are loaded randomly as I hardcode the number of images available for me, and generate a random index from 0 to this number.
mHeaderBackgroundImagesCount is a final:
private int getHeaderBackground() {
// Random index between 0 and mHeaderBackgroundImagesCount
Random rand = new Random();
int index = rand.nextInt(mHeaderBackgroundImagesCount) + 1;
return getResources()
.getIdentifier("image_" + index, "drawable", getPackageName());
}
As hard coding anything isn't normally the way to go in correct programming, I therefore like to dynamically find out how many 'image_X' drawables I have and set it to mHeaderBackgroundImagesCount.
I would like to do the same with strings from the strings.xml resource file as I'm also circulating some strings on every page load.
Solution Update
This update is inspired by Lalit Poptani's suggestion below. It includes syntax corrections and optimizations and have been tested to work.
private int countResources(String prefix, String type) {
long id = -1;
int count = -1;
while (id != 0) {
count++;
id = getResources().getIdentifier(prefix + (count + 1),
type, getPackageName());
}
return count;
}
System.out.println("Drawables counted: " + countResources("image_", "drawable"));
System.out.println("Strings counted: " + countResources("strTitle_", "string"));
Note: This method assumes that the resources counted start with index 1 and have no index holes like image_1 image_2 <hole> image_4 etc. because it will terminate on first occasion of id=0 thus resulting a faulty count.
If you are sure that your list of drawables will be in a sequence of image_1, image_2,... and so on then you can apply below logic,
int count = 0;
int RANDOM_COUNT = 10; //which is more than your drawable count
for (int i = 1; i < RANDOM_COUNT; i++){
int id = getResources().getIdentifier("ic_launcher_"+i,
"drawable", getPackageName());
if(id != 0){
count = + count;
}
else{
break;
}
}
Log.e(TAG, "This is your final count of drawable with image_x - "+ count);
You use this logic because of there will be no drawable with any name as image_x then id will be 0 and you can break the loop
I am not sure if it's possible to dynamically get the number of resources or drawables.
A way to circumvent this issue is to use string arrays as resources in strings.xml.
e.g.
<resources>
<string-array name="foo_array">
<item>abc1</item>
<item>abc2</item>
<item>abc3</item>
</string-array>
int count = getResources().getStringArray(R.array.foo_array).length;
Have a code that displays a random image:
Random rand = new Random();
int rndId = rand.nextInt(24) + 1;
imgName = "drw" + rndInt;
int id = getResources().getIdentifier(imgName, "drawable", getPackageName());
imageView.setImageResource(id);
How is it possible to implement read the image name by clicking on it in the program and create a new window with a description of the image that is unique to each.
Yes, you can get the Image Name if you have its resource id by using getResourceEntryName(resource_id),
String image_name = getResources().
getResourceEntryName(R.drawable.ic_launcher);
Log.d("name", image_name);
OUTPUT:
ic_launcher
I have various images in the res/drawable directory , i want to get a random image from it that has "module_" suffix, then load that into a drawable object.The image names are not not named consecutively i.e 1 ,2 ,3 etc , they have different names describing what it contains i.e. "apple", "banana" etc
Any ideas?
void populate() {
try {
ArrayList<Integer> number = new ArrayList<Integer>();
for (int i = 0; i <= 48; i++) // 1//
{
number.add(i + 1);
Log.i("nuber in loop ",number.add(i+1)+"");
}
Collections.shuffle(number);
Random r = new Random();
int Start = r.nextInt(number.size());
if (Start - 9 >= number.size() - 1)
Start -= 9;
Log.i("Start ",Start+"");
for (int i = 0; i <=8; i++)
{
String imgName = "img" + number.get(Start);
Log.i("imagename", imgName);
int id = getResources().getIdentifier(imgName, "drawable",
getPackageName());
Log.i("id", id + "");
ImgBtnArray[i].setImageResource(id);
Start++;
}
}
catch (Exception e) {
}
}
into the above function it will
48 is total no of images into drwable from thatany 9 randm img i'll get and it will check for not to allow duplicate no also
in to the above i've 1 to 49 imgs into sequence 1.png,2.png lyk that that is more easy way.. i think bt u can create string array may be this way u can do
I dont think its possible to a get a random image from the drawable directory, so i just hard coded an array with the images and randomly index into that.
How can I make an array that handles some of my images so that I can use it like this?:
ImageView.setImageResource(image[1]);
I hope I explained well...
To do that, you don't want an array of Drawable's, just an array of resource identifiers, because 'setImageResource' takes those identifiers. How about this:
int[] myImageList = new int[]{R.drawable.thingOne, R.drawable.thingTwo};
// later...
myImageView.setImageResource(myImageList[i]);
Or for a resizable version:
ArrayList<Integer> myImageList = new ArrayList<>();
myImageList.add(R.drawable.thingOne);
// later...
myImageView.setImageResource(myImageList.get(i));
First of all you have to get all drawable IDs of your pictures with the following method:
int android.content.res.Resources.getIdentifier(String name, String defType, String defPackage)
For example, you could read all drawable IDs in a loop:
int drawableId = resources.getIdentifier("picture01", "drawable", "pkg.of.your.java.files");
picture02...
picture03...
..and then save them into an Array of Bitmaps:
private Bitmap[] images;
images[i] = BitmapFactory.decodeResource(resources, drawableId);
Now you are able to use your images as array.
with respect of #Bevor, you can use getResources() method instead of android.content.res.Resources like this:
ArrayList<Integer> imgArr = new ArrayList<Integer>();
for(int i=0;i<5;i++){
imgArr.add(getResources().getIdentifier("picture"+i, "drawable", "pkg.of.your.java.files"));
}
Usage:
imageView.setImageResource((int)imgArr.get(3));
Kotlin code:
initialize below class:
private var drawables: Array<Drawable>
initialize drawables in 1 line:
drawables = arrayOf(
model.getDrawable(R.drawable.welcome_1),
model.getDrawable(R.drawable.welcome_2),
model.getDrawable(R.drawable.welcome_3)
)
my model.getDrawable() is
fun getDrawable(id: Int): Drawable {
return ResourcesCompat.getDrawable(context.resources, id, context.theme)!!
}
set drawable to imageView
holder.imageView.setImageDrawable(drawables[position])
String[] arrDrawerItems = getResources().getStringArray(R.array.arrDrawerItems); // Your string title array
// You use below array to create your custom model like
TypedArray arrDrawerIcons = getResources().obtainTypedArray(R.array.arrDrawerIcons);
for(int i = 0; i < arrDrawerItems.length; i++) {
drawerItemDataList.add(new DrawerItemModel(arrDrawerItems[i], arrDrawerIcons.getResourceId(i, -1), i == 0 ? true : false));
}
drawerItemAdapter = new DrawerItemAdapter(this, drawerItemDataList);
mDrawerList.setAdapter(drawerItemAdapter);