0

我希望最好的方法是从一个按钮点击类到一个活动列表中的一个随机活动......请提及我必须在java中放置它的位置......因为你可以看到我已经在尝试一种方法但我不能重复其他,由于某种原因,我得到一个 java 无法识别的 rand 错误.. 提前谢谢大家

    package com.example.whattodo2;

    import java.util.Random;

    import android.os.Bundle;
    import android.app.Activity;
     import android.content.Intent;

    import android.view.Menu;
    import android.view.View;

    import android.view.animation.Animation;
    import android.view.animation.AnimationUtils;
    import android.widget.Button;
    import android.widget.ImageView;


    public class Title extends Activity {



    Button reset, rts;
    ImageView title;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_title);
        Animation a = AnimationUtils.loadAnimation(this, R.animator.animation);
         ImageView rImage = (ImageView) findViewById(R.id.title);
         rImage.startAnimation(a);
         func();

        reset = (Button) findViewById(R.id.reset);
        reset.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        if(rand < 0.5){
                               Intent reset1 = new Intent(Title.this, MainActivity.class);
                               startActivity(reset1);
                           } else {
                               Intent reset2 = new Intent(Title.this, Question36.class);
                               startActivity(reset2); }
                    }
                });
        rts = (Button) findViewById(R.id.rts);
        rts.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        // TODO Auto-generated method stub
                        Intent rts=new Intent(Title.this,Rts.class);
                        startActivity(rts);

                    }
                });


    }

    protected void func() {
        // TODO Auto-generated method stub

    }

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



}
4

1 回答 1

1

将所有活动的名称存储在一个数组中,生成随机数并获取与随机生成的数字对应的活动。示例片段

    String[] title = new String[] { "Act1.class", "Act2.class","Act1.class","Act4.class","Act5.class"};

public String getRandomActivity(){
    Random randomGenerator = new Random();
            int randomInt = randomGenerator.nextInt(5);// pass number of elements as parameters
        return title[randomInt-1];//this should return class name

        }

Intent intent = new Intent(this,getRandomActivity())
startActivity(intent)
于 2013-08-14T11:22:32.477 回答