Set Android Image According to string - android

I have over 100 images in my drawable. Its basically a Category. I am calling data from server where a column included category. My images were named as cat_image1, cat_image2, cat_image3 etc. The server sending the corresponding srting as Image1, Image2, Image3 etc respectively. I think its not the way what I am doing
String catString = someJSONObject.getString(Config.POI_CATEGORY);
if (catString == "image1") {
someView.setImage(getResources().getDrawable(R.mipmap.image1));
}
else if (catString == "image2") {
someView.setImage(getResources().getDrawable(R.mipmap.image2));
}
else if (catString == "image3") {
someView.setImage(getResources().getDrawable(R.mipmap.image3));
}
...
...
...

Try something like this:
// catString = cat -> R.drawable.cat
int imageId = getResources().getIdentifier(catString, "drawable", getPackageName());
someView.setImage(imageId));
If you need a prefix use this:
// catString = cat -> R.drawable.ic_cat
int imageId = getResources().getIdentifier("ic_" + catString, "drawable", getPackageName());
someView.setImage(imageId));
You can also use a HashMap:
HashMap<String, Integer> hm = new HashMap<>();
// Put elements to the map
hm.put("cat", R.drawable.ic_some_cat_image);
hm.put("other cat", R.drawable.ic_other_cat);
for (int i = 0; i < typeofplace.length; i++) {
// You might want to check if it exists in the hasmap
someView.setImage(hm.get(catString));
}

Related

Change id name of ImageView with a String

Suppose we have :
ImageView imageView_A = findViewById(R.id.imageview_dhze);
ImageView imageView_B = findViewById(R.id.imageview_dhhkjhkze);
ImageView imageView_C = findViewById(R.id.imageview_dhkhkjze);
ImageView imageView_D = findViewById(R.id.imageview_dhhuihuybze);
I want to make a function like this :
changeImages(String NAME) {
imageView_1_NAME.setImageResource(R.drawable.img);
imageView_2_NAME.setImageResource(R.drawable.img);
imageView_3_NAME.setImageResource(R.drawable.img);
}
And for example, I could use it like this :
changeImage("A");
to obtain :
imageView_1_A.setImageResource(R.drawable.img);
imageView_2_A.setImageResource(R.drawable.img);
imageView_3_A.setImageResource(R.drawable.img);
It is possible ? How can I do that ?
You could put all the ImageViews in a HashMap like this:
HashMap<String, ImageView> imageViews = new HashMap<>();
Then you add the ImageViews to the HashMap:
imageViews.put("A", imageView_A);
imageViews.put("B", imageView_B);
...
And your function could look like this then:
private void changeImage(String name) {
imageViews.get(name).setImageResource(R.drawable.img);
}
In this case you should only call changeImage() when the HashMap contains a key with the same value of String name. If you are not sure if a key exists you need to check if imageViews.containsKey(name) first.
You can do that:
void changeImage(String NAME) {
int imageId = this.getResources().getIdentifier("imageView_" + NAME, "id", this.getPackageName());
if (imageId != 0) {
ImageView imageView = (ImageView) findViewById(imageId);
imageView.setImageResource(R.drawable.img);
}
}
I think what you're looking for is something like this
fun changeImage(which: String) {
when(which) {
"a" -> imageView_A.setImageResource(R.drawable.img)
"b" -> imageView_B.setImageResource(R.drawable.img)
"c" -> imageView_C.setImageResource(R.drawable.img)
"d" -> imageView_D.setImageResource(R.drawable.img)
else -> throw IllegalArgumentException("Unknown image view")
}
}
int[] images = {R.id.imageA,R.id.imageB,R.id.imageC,R.id.imageD,R.id.imageE};
int[] drawables = {R.drawable.imageA,R.drawable.imageB,R.drawable.imageC,R.drawable.imageD,R.drawable.imageE};
for(int i=0;i<5;i++)
{
findViewById(images[i]).setImageResource(drawables[i]);
}
It's easier.

how to access drawable pairs in hashmap

I try access to drawable resource that I put in hashmap object
this is my relevant code:
private void pairImagesCollection() {
mImages.put(R.drawable.img1, R.drawable.img1shadow);
mImages.put(R.drawable.img2, R.drawable.img2shadow);
mImages.put(R.drawable.img3, R.drawable.img3shadow);
mImages.put(R.drawable.img4, R.drawable.img4shadow);
}
private void checkMatch(View dragView, View view) {
ImageView target = (ImageView) view;
ImageView dragged = (ImageView) dragView;
Drawable image = dragged.getDrawable();
int imgId = mImages.get(Integer.valueOf(image)); // wrong, I don't know how to do it ?!
target.setImageResource(imgId);
}
Any help will be appraised!
You can use Iterator
Iterator itObj = hashMapOBJ.entrySet().iterator();
while (itObj .hasNext()) {
Map.Entry pair = (Map.Entry) itObj.next();
String Key = (String) pair.getKey();
Drawable Value = (Drawable) pair.getValue();
hashMapOBJ.put(Key, Value);
System.out.println("Key: " + Key + "------>" + Value);
}
int imgId = mImages.get(Integer.valueOf(image));
You cannot get Resource/Drawable Id from ImageView through Drawable. With codes above, You can set tag for ImageView dragged. After that get value with with your mImages.
Before you checkMatch, you set tag for dragView as Drawble, something like that:
dragged.setTag(R.drawable.img1);
And now you can getDrawableId and
imgId = getDrawableId(dragged);
private int getDrawableId(ImageView iv) {
return (Integer) iv.getTag();
}
You got a hashmap that stores references to an image and its shadow right?
Which image you want to put on the image view? You have to iterate through your map and put the image you want:
Iterator iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry pair = (Map.Entry)iterator.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
}
If you want to put the value image then you put the pair.getKey() else you put the pair.getValue().
target.setImageResource(R.drawable.xxx);

Android: Count strings and drawables

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;

Edit text of several buttons using a for loop

I have 16 buttons, whose names are "button1", "button2", and so on. Is there a way I can iterate through them using a for loop, by somehow appending the number value upon each iteration? Something like this:
for(int i = 1; i<17; i++ ){
Button b = (Button)findViewById(R.id.buttoni);
I know I can simply initialize each button in my onCreate() method, but I was just curious if I could do it in a way similar to my example code.
Thank you.
You can use getIdentifier :
for(int i = 1; i<17; i++ ){
int buttonId = getResources().getIdentifier("button"+i, "id", getPackageName());
Button b = (Button)findViewById(buttonId);
//Your stuff with the button
}
You can create an array of Button's and use getIdentifier method that allows you to get an identifier by its name.
final int number = 17;
final Button[] buttons = new Button[number];
final Resources resources = getResources();
for (int i = 0; i < number; i++) {
final String name = "btn" + (i + 1);
final int id = resources.getIdentifier(name, "id", getPackageName());
buttons[i] = (Button) findViewById(id);
}
In case someone is interested how to achive the same result using Java only
The solution above uses Android specific methods (such as getResources, getIdentifier) and can not be used in usual Java, but we can use a reflection and write a method that works like a getIdentifier:
public static int getIdByName(final String name) {
try {
final Field field = R.id.class.getDeclaredField(name);
field.setAccessible(true);
return field.getInt(null);
} catch (Exception ignore) {
return -1;
}
}
And then:
final Button[] buttons = new Button[17];
for (int i = 0; i < buttons.length; i++) {
buttons[i] = (Button) findViewById(getIdByName("btn" + (i + 1)));
}
NOTE:
Instead of optimizing this kind of code you should rethink your layout. If you have 17 buttons on the screen, a ListView is probably the better solution. You can access the items via index and handle onClick events just like with the buttons.

Getting random image from drawable directory with certain name suffix

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.

Categories

Resources