Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing image view background dynamically

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

like image 767
tejas Avatar asked Dec 06 '22 18:12

tejas


2 Answers

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

like image 86
tejas Avatar answered Dec 29 '22 06:12

tejas


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);
}
like image 22
Hiral Vadodaria Avatar answered Dec 29 '22 08:12

Hiral Vadodaria