动态更改图像视图背景

时间:2011-10-24 05:57:51

标签: android imageview

我的布局中有一组10个图像视图。我已将顺序ID也作为

给出了它们
android:id="@+id/pb1"

android:id="@+id/pb2"

现在我想动态更改背景。

    int totalPoi = listOfPOI.size();
    int currentPoi = (j/totalPoi)*10;
    for (i=1;i<=currentPoi;i++) {
          imageview.setBackgroundResource(R.drawable.progressgreen);
}

现在在for循环中我想动态设置图像视图背景。 i,e如果currentpoi值为3,则应更改3个图像视图的背景。 for循环迭代的次数应该改变许多图像视图的背景。希望现在问题很明确。

注意:我只有1个图像progressgreen,需要设置为10个图像视图

6 个答案:

答案 0 :(得分:5)

最后我通过以下方式做到了这一点,

我将所有id放在数组中

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

现在:

int pindex = 0;

for (pindex; pindex <currentPoi; pindex++) {

    ImageView img = (ImageView) findViewById(imageViews[pindex]) ;
    img.setImageResource(R.drawable.progressgreen);
}

现在,我可以动态更改图像。

@ goto10。谢谢你的帮助。我会调试你的观点,看看我身边出了什么问题

答案 1 :(得分:3)

创建一个ImageView数组:

ImageView views[] = new ImageView[10];
views[0] = (ImageView)findViewById(R.id.pb1);
...
views[9] = (ImageView)findViewById(R.id.pb10);

现在迭代循环以设置图像的背景:

for (i=1;i<=currentPoi;i++) 
{
    views[i-1].setBackgroundResource(R.drawable.progressgreen);
}

答案 2 :(得分:1)

你可以通过设置drawables的名称来做到这一点: 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()));
}

答案 3 :(得分:0)

你需要给你的ImageViews顺序id,例如“@ + id / pb1”和“@ + id / pb2”等。然后你可以像这样在循环中得到它们中的每一个:

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

com.your.package.name替换为您的应用程序包。

答案 4 :(得分:0)

试试这个代码...... 创建图像数组..

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

而不是修改你的代码

int totalPoi = listOfPOI.size();
int currentPoi = (j/totalPoi)*10;
for (i=1;i<=currentPoi;i++) {
      imageview.setBackgroundResource(mThumbIds[i]);}

答案 5 :(得分:0)

您可以创建一个ImageViews数组,然后在for循环中更改它们。

ImageView views[] = new ImageView[10];
views[0] = (ImageView)findViewById(R.id.imageView0);
...
views[9] = (ImageView)findViewById(R.id.imageView9);

然后将for循环更改为:

for (i=1;i<=currentPoi;i++) {
   views[currentPoi].setBackgroundResource(R.drawable.progressgreen);
}

数组从索引0开始,所以请确保这里没有一个错误的错误。