无法按下按钮上的随机图像

时间:2010-07-19 22:45:47

标签: java android image random

我想要做的只是让按钮随机加载图像。但是,按钮似乎不起作用。当我第一次加载活动时,它工作正常,并有一个随机的图像....但是当我按下按钮时,它不会像我需要的那样加载另一个。知道我错在哪里吗?它看起来很好:/

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



}

1 个答案:

答案 0 :(得分:3)

在按下按钮处理代码时,请更改

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

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