I am trying to make a view with random images. I have code and no errors but when I click the button to go to the random image it just stays the same.
My source is:
private static final Random rgenerator = new Random();
private static final Integer[] mImageIds =
{ R.drawable.img2, R.drawable.img1, R.drawable.img3, };
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Integer q = mImageIds[rgenerator.nextInt(mImageIds.length)];
ImageView iv = (ImageView) findViewById(R.id.imageviewyeah);
iv.setTag(q);
View nextButton = findViewById(R.id.next_image_button);
nextButton.setOnClickListener(this);
}
public void onClick(View v)
{
switch (v.getId())
{
case R.id.next_image_button:
Intent i = new Intent(this, RandomImage.class);
startActivity(i);
break;
}
}
Just keep a reference to your ImageView
and call setImageResource(int id)
with one of the random resources. You don't need to start a new Activity
to retrieve a random resource ID...
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Integer q = mImageIds[rgenerator.nextInt(mImageIds.length)];
final ImageView iv = (ImageView) findViewById(R.id.imageviewyeah);
View nextButton = findViewById(R.id.next_image_button);
nextButton.setOnClickListener(new OnClickListener() {
public void onClick(View V) {
int resource = mImageIds[rgenerator.nextInt(mImageIds.length)];
iv.setImageResource(resource);
}
});
}
I would change some things.
private static final Random rgenerator = new Random();
private ImageView iv;
private static final Integer[] mImageIds =
{ R.drawable.img2, R.drawable.img1, R.drawable.img3, };
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Integer q = mImageIds[rgenerator.nextInt(mImageIds.length)];
iv = (ImageView) findViewById(R.id.imageviewyeah);
changeImageResource();
View nextButton = findViewById(R.id.next_image_button);
nextButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
changeImageResource();
}
});
}
public void changeImageResource()
{
int i = regeneratos.nextInt(3);
iv.setImageResource(mImageIds[i]);
}
Hope this helps.