按钮单击以从活动列表中的一个活动转到随机

时间:2013-08-14 11:05:24

标签: android

我想要从按钮点击的一个班级到活动列表中的随机活动的最佳方式...请提及java中我必须放置它的位置...因为你可以看到iam已经尝试了一种方法但我不能重复其他,由于某种原因,我得到一个错误的兰德,java不承认..感谢提前家伙

    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;
    }



}

1 个答案:

答案 0 :(得分: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)