动态更改图像视图背景
我的布局中有一组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循环中,我想动态设置图像视图背景。如果currentpoi值为3,则应改变3个图像视图的背景。 for循环迭代了许多图像视图背景应该改变的时间。希望问题现在已经清楚。
注:我有一个需要被设置为10个的图像视图
只有1个图像progressgreen
最后我做了这在t他下面的方式,
我把所有的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。谢谢你的帮助。我会调试你的观点,看看我的身边出了什么问题
你需要给你的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
与应用程序的包。
试试这个代码..... 创建图像阵列..
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]);}
你可以让你的ImageViews的数组,然后更改它们在你的循环。
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,所以一定要确保有没有一个差一错误在这里。
您可以通过设置可绘制的名义这样做是这样的: 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()));
}
这不会在多个ImageView上设置背景。它在同一个ImageView上多次设置背景。 – goto10
创建一个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);
}
你能展示完整的代码并清楚解释吗?你有多少可绘制的。列出可绘制的s。 –
你的问题又是什么? – Reno