How do I reference the image returned in the random image array?
I am putting together some codes and attempting to assign a wallpaper with the attached code. Th开发者_运维问答e random image part works, the assign image to wallpaper works, but I do not see how to get the exact image shown to be the image for the wallpaper.
public class RandomImage extends Activity implements OnClickListener{
private Integer [] mImageIds = {
R.drawable.big1,
R.drawable.big2,
R.drawable.big3,
};
private static final Random rgenerator = new Random();
private ImageView iv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.winner);
Integer q = mImageIds[rgenerator.nextInt(mImageIds.length)];
iv = (ImageView) findViewById(R.id.imageView1);
iv.setImageResource(q);
iv.setImageResource(mImageIds[rgenerator.nextInt(mImageIds.length)]);
View setButton = findViewById(R.id.set_wallpaper);
setButton.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.set_wallpaper:
WallpaperManager myWallpaperManager =
WallpaperManager.getInstance(getApplicationContext());
try {
//How to reference the image selected in above random array?
myWallpaperManager.setResource(????);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Why not declaring an int class variable that stocks the id, e.g:
int lastImageRef;
...
lastImageRef = mImageIds[rgenerator.nextInt(mImageIds.length)];
iv.setImageResource(lastImageRef);
...
myWallpaperManager.setResource(lastImageRef);
精彩评论