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);
Related
Let say I have 2 arrays
Array1 = 1,2,3,4,5
Array2 = a,b,c,d,e
String[] array = getResources().getStringArray(R.array.Array1);
That's work fine. But I don't want to use the code above again with another line
String[] array = getResources().getStringArray(R.array.Array2);
How do I get the below lines to work if
I had declared xxx as variable for array name
String xxx = Array1;
String[] array = getResources().getStringArray(R.array.xxx);
You can:
int xxx = R.array.Array1; //change to integer
String[] array = getResources().getStringArray(xxx); //pass the whole id
Instead of passing just the name of the resource, pass the whole ID (as integer).
If you still want to pass the name as string, you can:
String xxx = "Array1";
int resourceId = getResources().getIdentifier(xxx, "array", getPackageName());
String[] array = getResources().getStringArray(resourceId);
reference of the second option: https://stackoverflow.com/a/3476447/9038584
A simple util method in your activity or service:
String[] getArray(int id) {
return getResources().getStringArray(id);
}
Usage:
String[] array1 = getArray(R.array.array1);
int imgs[] =
{
R.drawable.a,
R.drawable.b,
R.drawable.c,
R.drawable.d,
R.drawable.e,
// R.drawable.abc,
};
I want to do that thing with the help of if loop.
I hope I understood you correctly and what you're looking for is dynamic creation of that array.
For example, if your drawables are named like R.drawable.image0, R.drawable.image1, etc. And there are N of them you can use the following code.
int imgs[] = new int[N];
for (int i = 0; i < N; i ++) {
imgs[i] = this.getResources().getIdentifier("image" + i, "drawable", this.getPackageName());
}
EDIT:
Well, there's some confusion in the comment section.
If you want to keep your drawable names as they are (a, b, c) you would need to define them too. For example
String[] names = {"a", "b", "c"};
int imgs[] = new int[names.length];
for (int i = 0; i < names.length; i ++) {
imgs[i] = this.getResources().getIdentifier(names[i], "drawable", this.getPackageName());
}
But as you see, you're not achieving much by using that loop in this case, because you still have to manually type all the names.
One Solution is create a model class like this :
class DrawableClass{
int id;
Drawable drawable;
}
create objects of this with incremental id in each object. and in loop parse with respect to id.
In the res/drawable-mdpi folder I have 26 letter images, named big_0.png to big_25.png.
I would like to add them all (and ignore any other images in the folder) to a hash map:
private static HashMap<Character, Drawable> sHash =
new HashMap<Character, Drawable>();
Initially I was planning something like:
private static final CharacterIterator ABC =
new StringCharacterIterator("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
int i = 0;
for (char c = ABC.first();
c != CharacterIterator.DONE;
c = ABC.next(), i++) {
String fileName = "R.drawable.big_" + i;
Drawable image = context.getResources().getDrawable(fileName);
sHash.put(c, image);
}
But then I've realized that R.drawable.big_0 to R.drawable.big_25 are of type int and not String.
So please advise me, how to iterate through the 26 images correctly?
Use getResources().getIdentifier() to convert "R.drawable.big_" + i into the resource ID value that you would use with getDrawable().
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
there are many images in drawable foder so instead manually creating array of all image resource ids , i want to get all images dynamically of drawable folder in array.
currently i m using this code:
for(int i=1;i<=9;i++)
{
int imageKey = getResources().getIdentifier("img"+i, "drawable", getPackageName());
ImageView image = new ImageView(this);
image.setId(imgId);
image.setImageResource(imageKey);
image.setScaleType(ImageView.ScaleType.FIT_XY);
viewFlipper.addView(image, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
imgId++;
}
but in that code i need to manually edit the image name to get the resource id but i want to get all image with any name..
you can Use Reflection to achieve this.
import the Field class
import java.lang.reflect.Field;
and then write this in your code
Field[] ID_Fields = R.drawable.class.getFields();
int[] resArray = new int[ID_Fields.length];
for(int i = 0; i < ID_Fields.length; i++) {
try {
resArray[i] = ID_Fields[i].getInt(null);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
resArray[] now holds references to all the drawables in your application.
Well, If your image names are img1, img2 and so on, then you can create a variable like
String url = "drawable/"+"img"+i;
int imageKey = getResources().getIdentifier(url, "drawable", getPackageName());
you can also replace your getPackageName() method by your package name like "com.android.resource"
Simply,the general function is
public int getIdentifier(String name, String defType, String defPackage)