views:

26

answers:

1

What i'm trying to do is just simply have the button load an image at random. However, the button doesn't seem to be working. When i first load the activity there it works fine and there is a random image....But when i press the button it's not loading another like i need it to. Any idea what i have wrong here? It looks fine to me :/

package com.my.package;


import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View.OnClickListener;

public class Randomimage extends Activity implements OnClickListener{


    private Integer [] mImageIds = { 
            R.drawable.one, 
            R.drawable.two, 
            R.drawable.three, 
            };
    private static final Random rgenerator = new Random();

    private ImageView iv;



@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);
    iv.setImageResource(q);


    View nextButton = findViewById(R.id.next_image_button);
    nextButton.setOnClickListener(this);

}


    @Override
    public void onClick(View v) {
    switch (v.getId()) {
    case R.id.next_image_button:
        iv.setImageResource(rgenerator.nextInt(mImageIds.length));
        break;
    }

}
    @Override
    public boolean onCreateOptionsMenu (Menu menu) {
        super.onCreateOptionsMenu(menu);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu3, menu);
        return true;
    }

@Override
public boolean onOptionsItemSelected (MenuItem item) {
        switch (item.getItemId()) {
        case R.id.menu:
            startActivity(new Intent(this, Main.class));
            return true;
        case R.id.startnhie:
            startActivity(new Intent(this, startnhie.class));
            return true;

}
return false;
    }



}
+3  A: 

In your button press handling code, change

iv.setImageResource(rgenerator.nextInt(mImageIds.length));

to

iv.setImageResource(mImageIds[rgenerator.nextInt(mImageIds.length)]);
Andy Zhang
that was it! you rock great eye!
brybam