random image in Android?

2019-06-04 07:48发布

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

2条回答
We Are One
2楼-- · 2019-06-04 08:21

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);
         }
    });
}
查看更多
对你真心纯属浪费
3楼-- · 2019-06-04 08:34

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.

查看更多
登录 后发表回答