2010-07-19 88 views
1

我想要做的只是簡單地讓按鈕隨機加載圖像。但是,該按鈕似乎沒有工作。當我第一次加載活動那裏它工作正常,有一個隨機圖像....但是當我按下按鈕,它不會加載另一個像我需要它。任何想法我在這裏有什麼錯誤?這看起來好像沒什麼問題:/加載按鈕上的隨機圖像時遇到問題

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

在你按下按鈕處理代碼,改變

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

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

原來如此!你搖滾很棒的眼睛! – brybam 2010-07-20 00:12:53