Iterate through certain images in res/drawable-mdpi - android

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().

Related

Converting an edittext value to an array of integers

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;
}

How to randomely display images when the activity starts

I want to display images randomly when my activity starts. I am using the following code to execute it.
final ImageView img = (ImageView) findViewById(R.id.imgRandom);
final String str = "img_" + rnd.nextInt(2);
img.setImageDrawable(getResources().getDrawable(
getResourceID(str, "drawable", getApplicationContext())));
}
protected final static int getResourceID(final String resName,
final String resType, final Context ctx) {
final int ResourceID = ctx.getResources().getIdentifier(resName,
resType, ctx.getApplicationInfo().packageName);
if (ResourceID == 0) {
throw new IllegalArgumentException(
"No resource string found with name " + resName);
} else {
return ResourceID;
}
}
PROBLEM: This code only randomly generates first two images present in my drawable, whereas i have a total of 8 images.
Thanks in advance.
P.S the name of my images are img_0 , img_1, img_2, img_3, img_4, img_5, img_6, img_7
Use HashMap to store your image names associated with a key ,
HashMap<Integer, String> meMap=new HashMap<Integer, String>();
meMap.put(0,"img_0"); // add other images as 1, 2, 3
Use Random class to generate number including 0 and less than 8
Random rnd = new Random();
int value = rnd.nextInt(8);
Get the relevant map object according to the generated key(random integer) and get the respective image name and load it.

Get a list of filenames in a drawable resource directory

I want to get a list of certain filenames in a drawable resource directory (at runtime, not using XML). I guess, I would need to distinguish certain files from others. So ...
*res/drawable-hdpi/mysubdir
-- x-one.png
-- one.png
-- x-two.png
-- two.png
-- x-three.png
-- three.png
*
I want to put the x-*.png filenames into a List<String>. Is this possible?
Borrowing some code from another question, I can get all the drawables, but I don't see a way to distinguish one from another in a meaningful way.
private void getDrawableResources() {
final R.drawable drawableResources = new R.drawable();
final Class<R.drawable> drawableClass = R.drawable.class;
final Field[] fields = drawableClass.getDeclaredFields();
final List<Integer> resourceIdList = new ArrayList<Integer>();
for (int i = 0, max = fields.length; i < max; i++) {
final int resourceId;
try {
resourceId = fields[i].getInt(drawableResources);
resourceIdList.add(resourceId);
}
catch (Exception e) {
continue;
}
}
Resources resources = this.getActivity().getResources();
for (int i = 0; i < resourceIdList.size(); i++) {
Drawable drawable = resources.getDrawable(resourceIdList.get(i));
resourceIdList.get(i) + "): " + drawable.toString());
}
}
Resource directories do not support subdirectories.
Use FileNameFilter while getting list of files in a directory.
File dir = new File(dirLocation);
if(dir.exists() && dir.isDirectory())
{
File[] files = dir.listFiles(new FilenameFilter()
{
public boolean accept(File dir, String name)
{
return name.contains("X-");
}
});
}

How to assign Image Resource to ImageView with String in Android

I am trying to create a routine that will assign a card image to an ImageView without using something like this: R.drawable.card_10clover. I would prefer to use a string, but the way I'm doing it doesn't work.
String imgRes = "R.drawable.card_";
int num = 10;
imgRes += "10";
String suit = "clover";
imgRes += "suit;
ImageView card = (ImageView) findViewById(R.id.imgcard);
card.setImageResource(imgRes);
Unfortunately setImageResource only takes an int. Please help.
Thank you,
Jack Blue
Use getIdentifier (String name, String defType, String defPackage);
Your imgRes does not need the prefix R.drawable
String imgRes = "card_";
int num = 10;
imgRes += "10";
String suit = "clover";
imgRes += "suit;
ImageView card = (ImageView) findViewById(R.id.imgcard);
int resourceId = getResource().getIdentifier (imgRes, "drawable", "com....");
card.setImageResource(resourceId);

Android: How can I make a Drawable array?

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);

Categories

Resources