[英]intent activity switching to random activity
我試圖在單擊按鈕時從活動1切換到活動2。 我知道該怎么做。 我不知道是如何獲得它的,所以50%的時間去了活動2,另外50%的時間去了活動3。對不起,我知道這是一個非常明顯的問題。 我對此不陌生,所以請您說明一下,還提供類似的效果,例如從5種不同的指定活動中完全隨機化。 在此先感謝...下面的意圖代碼。 請解釋使用我的代碼(如果可能)。
yes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent yes1=new Intent(MainActivity.this,Question2.class);
startActivity(yes1);
不在我的頭上,所以它可能無法完全編譯:-),但是這個想法很合理
List<Class<? extends Activity>> activities = new ArrayList<Class<? extends Activity>>();
activities.add(Question.class);
activities.add(Question2.class);
Random generator = new Random();
Class<? extends Activity> randomActivity = activities.get(generator.nextInt(activities.size()));
Intent intent = new Intent(this, randomActivity);
startActivity(intent);
您可以只使用Random
類來確定下一個意圖。 請以此代碼段為例。-
Intent newIntent = null;
Random rand = new Random();
int index = rand.nextInt(4);
switch (index) {
case 0:
newIntent = new Intent(this, Question1.class);
break;
case 1:
newIntent = new Intent(this, Question2.class);
break;
case 2:
newIntent = new Intent(this, Question3.class);
break;
case 3:
newIntent = new Intent(this, Question4.class);
break;
}
startActivity(newIntent);
嘗試這個:
yes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
double rand = Math.random();
if(rand < 0.5){
Intent yes1 = new Intent(MainActivity.this, Question2.class);
startActivity(yes1);
} else {
Intent yes2 = new Intent(MainActivity.this, Question3.class);
startActivity(yes2);
}
}
});
在5種不同活動之間隨機切換的情況類似。 您可能會對其進行優化,因此,如果您有許多不同的活動,則不只是在所有不同選項之間進行分支。
您可以設置類名稱的String Array
,例如
String[] classes = new String[3];
classes[0] = Activity1;
classes[1] = Activity2;
classes[2] = Activity3;
然后使用Random
數在它們之間選擇,然后單擊以執行類似操作
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Random r = new Random();
int number = r.nextInt(4);
String curClass = classes[number);
Intent yes1=new Intent(MainActivity.this,Class.forName(curClass));
startActivity(yes1);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.