Android中的随机图片?

时间:2011-05-02 19:14:56

标签: android eclipse image random

我试图用随机图像制作视图。我有代码,没有错误,但当我点击按钮转到随机图像时,它就保持不变。

我的来源是:

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 个答案:

答案 0 :(得分:1)

只需保留对ImageView的引用,并使用其中一个随机资源调用setImageResource(int id)。您无需启动新的Activity来检索随机资源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);
         }
    });
}

答案 1 :(得分:0)

我会改变一些事情。

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

希望这有帮助。