2014-01-08 40 views
-2

我有一個隨機數發生器,我需要根據不同的Int值顯示不同的圖像, 。Imageview根據Int顯示不同的圖像

例如,當randomNumber是讓我們說1,我需要顯示特定的文字和圖片 ,當數爲10的另一個特定的文本和圖像等。

可我甚至做到這一點與ImageView的,我不知道從哪裏開始?

package com.example.drinktivity; 

    import android.os.Bundle; 
    import android.app.Activity; 
    import android.content.Intent; 
    import android.view.Menu; 
    import android.view.View; 
    import android.widget.Button; 
    import android.widget.TextView; 


    public class Main2Activity extends Activity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main2); 


Button back = (Button) findViewById(R.id.buttonback); // Here the R.id.button1 is the button from you design 
back.setOnClickListener(new View.OnClickListener() { 
public void onClick(View arg0) { 
Intent i = new Intent(Main2Activity.this, MainActivity.class); 
startActivity(i); 
} 
}); 

ImageView image = (ImageView) findViewById(R.id.imageView1); 
Bundle bundle = getIntent().getExtras(); 
int random = bundle.getInt("Value"); 
TextView text = (TextView) findViewById(R.id.textView1); 
if (random==1) { 
    text.setText(""); 
} 
if (random==2) { 
    text.setText(""); 
} 
if (random==3) { 
    text.setText(""); 
} 
if (random==4) { 
    text.setText(""); 
} 
if (random==5) { 
    text.setText(""); 
} 
if (random==6) { 
    text.setText(""); 
} 
if (random==7) { 
    text.setText(""); 
} 
if (random==8) { 
    text.setText(""); 
} 
if (random==9) { 
    text.setText(""); 
} 
if (random==10) { 
    text.setText(""); 
} 


} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.main, menu); 
    return true; 
} 

    } 
+0

請添加一些代碼的.. –

+0

請告訴你的隨機數限制。 –

回答

0
int[] i = {R.drawable.drawable1, R.drawable.drawable2, R.drawable.drawable2,  R.drawable.drawable4, R.drawable.drawable5,}; 
Random rand = new Random(); 
int n = rand.nextInt(5); 
imageView.setBackground(getResources().getDrawable(i[n])); 
0

考慮您的int值作爲INT隨機 和你的隨機不包含數字1到5 ,那麼你可以做到這一點。

if(random==1){ 

imageview.setImageBitmap(yourbitmap); 

//here imageview is your imageview. and then bitmap you want when the number generated is 1. 

} 
0

這絕對是可能的,但有很多方法可以做到這一點。我認爲你想要的主要方法是生成一個隨機數字,並根據該數字從資源中選擇一幅圖像。你可以像這樣的檢索資源:

context.getResources().getIdentifier(i.getIcon(), "drawable", context.getPackageName()) 
1

創建繪製陣列

public static final int[] im_smiley_drawable_smile_old = { 
        R.drawable.im_smiley_happy, R.drawable.im_smiley_sad, 
        R.drawable.im_smiley_winking, 
        R.drawable.im_smiley_tongue_sticking_out, 
        R.drawable.im_smiley_surprised, R.drawable.im_smiley_kissing, 
        R.drawable.im_smiley_yelling, R.drawable.im_smiley_cool} 

發送ramdom號碼這個數組,你會得到隨機圖像