如何使我的代码随机后不重复活动?

时间:2017-01-18 07:01:34

标签: android

我只是做了随机活动,我的问题是如何防止已经打开的活动再次打开。例如,我从1-5中选择,我选择3,我不应该再次选择3,因为我已经选择了它,只选择剩下的数字。

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

public void onBackPressed() {
}

public void openNewActivity(View view) {
    Random rnd = new Random();
    int x = rnd.nextInt(3) + 1;
    Intent intent = new Intent();
    switch (x) {
        case 1:
            intent.setClass(this, Question1.class);
            break;
        case 2:
            intent.setClass(this, Question2.class);
            break;
        case 3:
            intent.setClass(this, Answer1.class);
            break;
    }
    startActivity(intent);
}

2 个答案:

答案 0 :(得分:1)

我建议你把Activity类放到这样的数组中:

private ArrayList<Class<? extends Activity>> activitiesNotOpened;

onCreate

activitiesNotOpened = new ArrayList<>();
activitiesNotOpened.add(Question1.class);
activitiesNotOpened.add(Question2.class);
activitiesNotOpened.add(Answer1.class);

现在您可以在openNewActivity中执行此操作:

if (activitiesNotOpened.size() > 0) {
    Random rnd = new Random(); // Note: I suggest you to put this line at class level
    int x = rnd.nextInt(activitiesNotOpened.size());
    Intent intent = new Intent();
    intent.setClass(this, activitiesNotOpened.get(x));
    activitiesNotOpened.remove(x);
    startActivity(intent);
}

这是如何运作的?

这样做的原因是我们从数组列表中选择一个随机活动。然后,每次打开新活动时,我们都会删除从数组列表中打开的活动。这样,将不会再次选择相同的活动。

答案 1 :(得分:0)

首先创建一个列表并在其中添加1到3个数字,

    List<Integer> list = new ArrayList<>();


    for(int i=1;i<=3;i++)
    {
        list.add(i); // add 1 to 3 in list
    }

然后改变你的方法,

public void openNewActivity(View view) {
        Random rnd = new Random();
        int x = rnd.nextInt(Collections.max(list)) + 1; //Collections.max(list) returns maximum value availble in the list
        Intent intent = new Intent();
        switch (x) {
            case 1:
                intent.setClass(this, Question1.class);
                break;
            case 2:
                intent.setClass(this, Question2.class);
                break;
            case 3:
                intent.setClass(this, Answer1.class);
                break;
        }
        list.remove(list.indexOf((x-1))); //remove that number from list
        startActivity(intent);
    }