Changing image view background dynamically - android

I have a a set of 10 imageviews in my layout. I have given them sequential id's also as
android:id="#+id/pb1"
android:id="#+id/pb2"
Now I want to change background dynamically.
int totalPoi = listOfPOI.size();
int currentPoi = (j/totalPoi)*10;
for (i=1;i<=currentPoi;i++) {
imageview.setBackgroundResource(R.drawable.progressgreen);
}
Now inside the for loop I want to set the image view background dynamically. i,e if the currentpoi value is 3, background of 3 image views should be changed. What ever the times the for loop iterates that many image view's background should be changed. Hope the question is clear now.
Note : I have only 1 image progressgreen that need to be set to 10 image views

Finally I did this in the following way,
I placed all the id's in the array as
int[] imageViews = {R.id.pb1, R.id.pb2,R.id.pb3,R.id.pb4,R.id.pb5,R.id.pb6,R.id.pb7,R.id.pb8,R.id.pb9,R.id.pb10};
Now:
int pindex = 0;
for (pindex; pindex <currentPoi; pindex++) {
ImageView img = (ImageView) findViewById(imageViews[pindex]) ;
img.setImageResource(R.drawable.progressgreen);
}
Now, I am able to change the images dynamically.
#goto10. Thanks for your help. I will debug your point to see what went wrong in my side

Create an ImageView array:
ImageView views[] = new ImageView[10];
views[0] = (ImageView)findViewById(R.id.pb1);
...
views[9] = (ImageView)findViewById(R.id.pb10);
Now iterate the loop to set the background of images like this:
for (i=1;i<=currentPoi;i++)
{
views[i-1].setBackgroundResource(R.drawable.progressgreen);
}

you can do this by setting the name of drawables something like:
img_1, img_2, img_3...
for (i=1;i<=currentPoi;i++)
{
ImageView imageview=(ImageView) findViewById(getResources().getIdentifier("imgView_"+i, "id", getPackageName()));
imageview.setImageResource(getResources().getIdentifier("img_"+i, "drawable", getPackageName()));
}

Try this code.....
Create image Array..
private Integer[] mThumbIds = { R.drawable.bg_img_1, R.drawable.bg_img_2,
R.drawable.bg_img_3, R.drawable.bg_img_4, R.drawable.bg_img_5 };
And than modify your code
int totalPoi = listOfPOI.size();
int currentPoi = (j/totalPoi)*10;
for (i=1;i<=currentPoi;i++) {
imageview.setBackgroundResource(mThumbIds[i]);}

You could make an array of your ImageViews and then change them in your for loop.
ImageView views[] = new ImageView[10];
views[0] = (ImageView)findViewById(R.id.imageView0);
...
views[9] = (ImageView)findViewById(R.id.imageView9);
and then change your for loop to:
for (i=1;i<=currentPoi;i++) {
views[currentPoi].setBackgroundResource(R.drawable.progressgreen);
}
Arrays start at index 0, so make sure there's not an off-by-one error in here.

You'll need to give your ImageViews sequential ids, such as "#+id/pb1" and "#+id/pb2", etc.. Then you can get each of them in the loop like this:
for (i=1;i<=currentPoi;i++) {
// Find the image view based on it's name. We know it's pbx where 'x' is a number
// so we concatenate "pb" with the value of i in our loop to get the name
// of the identifier we're looking for. getResources.getIdentifier() is able to use
// this string value to find the ID of the imageView
int imageViewId = getResources().getIdentifier("pb" + i, "id", "com.your.package.name");
// Use the ID retrieved in the previous line to look up the ImageView object
ImageView imageView = (ImageView) findViewById(imageViewId);
// Set the background for the ImageView
imageView.setBackgroundResource(R.drawable.progressgreen);
}
Replace com.your.package.name with your application's package.

Related

How can I access ImageView that was dynamically created in LinearLayout to use it source else where?

How can I get the source id (id.drawable.blablabla) of an ImageView that I created dynamically (like this):
ImageView image = new ImageView(this);
image.setImageResource(imageId);
image.setLayoutParams(new LinearLayout.LayoutParams(size, size));
layout.addView(image);
I wanna use getChildAt method on my layout if it is possible. I just need that image else where and I don't have control what image it actually is becouse they creation is based on rand. Index of that element is enough for me
ANSWER
I jsut find cool solution! I just add image.setTag(imageId) line of code to my method and then when I need rolled image I can simply use id under tag, thanks for help :)
I get dynamic drawable like this:
int id = getResources().getIdentifier("action" + String.valueOf(randomint), "drawable", getPackageName());
Drawable d = getResources().getDrawable(id);
And then add them to an imageview. Which you then add to a Linear layout.
Does this solve your problem?
ImageView image = new ImageView(this);
image.setId(1 + 28000); // Id in integer suppose we use this value where 1 is dynamic value which you wants to add in your imageview.
image.setImageResource(imageId);
image.setLayoutParams(new LinearLayout.LayoutParams(size, size));
layout.addView(image);
// Now here is code to get its id which you want in integer :
image.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
System.out.println("your id" + (arg0.getId() - 28000));
}
});
You can get the drawable like
Drawable myDrawable = iv.getDrawable();
You can compare it with a drawable resource like
if(iv.getDrawable()==getResources().getDrawable(R.drawable.image1)){
//do work here
}
credit https://stackoverflow.com/a/20765566/4211264

Loading dynamic imageviews in loop in Android creating gaps

I am reading data from a SOAP service and then using that data to load images from the res folder locally. I am using a loop because there will always be six images being loaded. This is my code :
final TableLayout tblLay = (TableLayout)findViewById(R.id.lottotl);
final LayoutParams params = new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
for(int i=2;i<9;i++) {
final ImageView image = new ImageView(LastDraw.this);
image.setLayoutParams(trparams);
image.setMaxHeight(20);
image.setMaxWidth(20);
String imgName = "img_" + split[i].substring(split[i].indexOf("=") + 1);
int id = getResources().getIdentifier(imgName, "drawable", getPackageName());
image.setImageResource(id);
row2.setLayoutParams(params);
row2.addView(image);
}
tblLay.addView(row2);
The issue I am having is that there is a gap between the first image and the consecutive images.
It looks like this (each number representing an image):
1.........23456
I am thinking it has to do with the layout of the row in the tablelayout, I could be wrong.
Thank you
Anyone?
Figured it out ... feel kind of stupid but, I learnt something! I load a textview into the first row and then the imageviews into the second row. The textview is in the first column and its width is making the first column stretch ... THAT is why there is a gap.

Android ImageView setImageResource in code

I have an imageView that I want to display a little icon of the country that you are currently in. I can get the country code, but problem is I can't dynamically change the imageView resource. My image files are all lowercase (Example: country code=US, image file=us)
My code (countryCode is the current countryCode in uppercase letters):
String lowerCountryCode = countryCode.toLowerCase();
String resource = "R.drawable." + lowerCountryCode;
img.setImageResource(resource);
Now, of course this will not work because setImageResource wants an int, so how can I do this?
One easy way to map that country name that you have to an int to be used in the setImageResource method is:
int id = getResources().getIdentifier(lowerCountryCode, "drawable", getPackageName());
setImageResource(id);
But you should really try to use different folders resources for the countries that you want to support.
This is how to set an image into ImageView using the setImageResource() method:
ImageView myImageView = (ImageView)v.findViewById(R.id.img_play);
// supossing to have an image called ic_play inside my drawables.
myImageView.setImageResource(R.drawable.ic_play);
you use that code
ImageView[] ivCard = new ImageView[1];
#override
protected void onCreate(Bundle savedInstanceState)
ivCard[0]=(ImageView)findViewById(R.id.imageView1);
You can use this code:
// Create an array that matches any country to its id (as String):
String[][] countriesId = new String[NUMBER_OF_COUNTRIES_SUPPORTED][];
// Initialize the array, where the first column will be the country's name (in uppercase) and the second column will be its id (as String):
countriesId[0] = new String[] {"US", String.valueOf(R.drawable.us)};
countriesId[1] = new String[] {"FR", String.valueOf(R.drawable.fr)};
// and so on...
// And after you get the variable "countryCode":
int i;
for(i = 0; i<countriesId.length; i++) {
if(countriesId[i][0].equals(countryCode))
break;
}
// Now "i" is the index of the country
img.setImageResource(Integer.parseInt(countriesId[i][1]));
you may try this:-
myImgView.setImageDrawable(getResources().getDrawable(R.drawable.image_name));

Displaying image based on string chosen?

I have a code rite now that just generates a random drink combination from an array, what I need to do is have a different image assigned to each choice and have it display that image.
Here is my code for a random drink:
if(Vodka.equals(true)){
final TextView text2 = (TextView) findViewById(R.id.display2);
randomIndex = random.nextInt(array_city.Vodka.length);
text2.setText(array_city.Vodka[randomIndex]);
}
Say this code spits out "Smirnof" then i display a picture of the bottle, it spits out "Sky" then changes to a picture of that bottle. How would i do this without making an if statement for each option, my arrays are very long and that would be alot of if statements i was just Hoping that there is an easier way to do it?
Thanks anybody for your help! it is very much appreciated I have been stuck on this for a while.
===============================================================
#Joan
Here is what i am trying to put together using your code:
//Run option Vodka
if(Vodka.equals(true)){
final TextView text2 = (TextView) findViewById(R.id.display2);
randomIndex = random.nextInt(array_city.Vodka.length);
text2.setText(array_city.Vodka[randomIndex]);
final ImageView image = (ImageView) findViewById(R.id.imageView1);
int Cimage = getResources().getIdentifier(array_city.Vodka[randomIndex], null, "com.famousmods.what.should.i.drink");
image.setImageResource(Cimage);
}
Here is what my array looks like (a smaller example):
public static final String[] Vodka = {"Absolut Vodka","Finlandia","Ketel One","Polmos Krakow","Skyy","smirnoff vodka",
"Stolichnaya","Fleischmann's","Gilbey's","Gordon's","Wolfschmitt","Five-O-Clock"};
I have put the file "smirnoff_vodka.png" into my res/drawables as an example but it doesnt work?
You can use getResources().getIdentifier("image_name", null, "your_application_package"); on your context to retrieve the image id. Then you can use this id as you would use R.id.image_name.
EDIT: It needs to be "drawable" instead of null. See below.

Android fill array with ImageViews

I want an array of imageviews, but I don't know how to fill it with an object of type imageview.
ImageView[] forAdapter = new ImageView[imageIds.size()];
for(int i = 0; i < imageIds.size(); i++)
{
ImageView mImageView = new ImageView(context);
forAdapter[i] = mImageView.setImageDrawable(((imagesPulled.get(imageIds.get(i)))));
}
this doesn't work because .setImageDrawable does not return an imageview, and I dont know of any object that actually does!
I considered using drawables in an array, but I'm ultimately setting an arrayadapter for a listview, and I cant make a R.layout with drawables (I'll get a class cast exception because the xml file is using an ImageView not drawable type),so I only have ImageViews to put into an array - unless I'm approaching the problem wrong.
Your code is almost there! I'm just gonna make a small change and comment on it below:
ImageView[] forAdapter = new ImageView[imageIds.size()];
for(int i = 0; i < imageIds.size(); i++)
{
forAdapter[i] = new ImageView(context);
forAdapter[i].setImageDrawable(imagesPulled.get(imageIds.get(i)));
}
First: If you want to initialize forAdapter[i], you don't need to create a new variable and assign it to it. Just do it there:
forAdapter[i] = new ImageView(context);
Setting the image (using setImageDrawable, setImageResource, etc) doesn't return anything. It's an operation you do on the image itself so all you gotta do is call the method from the variable you want to modify:
forAdapter[i].setImageDrawable(imagesPulled.get(imageIds.get(i)));
You're done :)
If you have any doubts just ask in the comments.
Hope it helps.
Your mImageView is ImageView itself.
So, forAdapter[i] = mImageView should work fine. If you use additional actions, you can do them before assignment.

Categories

Resources