在Android中选择随机按钮来设置文本

时间:2015-01-15 09:52:08

标签: android button random textview

我有一个问题和两个按钮的测验,其中一个是真的,一个是假的。如何将文本随机放入按钮中,以便正确的答案并不总是与同一个按钮相关联。

        @Override
        public void onClick(View v) {
            if(Integer.parseInt(answer1.getText().toString()) == c){

                 Toast bf = Toast.makeText(getApplicationContext(), "Correct",Toast.LENGTH_SHORT);
                 bf.show();

             }
            else{
                Intent i = new Intent(getApplicationContext(), TopActivityMath.class);
                startActivity(i);
            }

        }
    });

    answer2.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if(Integer.parseInt(answer2.getText().toString()) == c){

                 Toast bf = Toast.makeText(getApplicationContext(), "Correct",Toast.LENGTH_SHORT);
                 bf.show();

             }
            else{
                Intent i = new Intent(getApplicationContext(), TopActivityMath.class);
                startActivity(i);
            }

        }
    });

2 个答案:

答案 0 :(得分:1)

问题不是很清楚,但为了得到一些随机的东西,你可以使用这个

Random rand = new Random();
int n = rand.nextInt(2); // Gives n such that 0 <= n < 2

含义n会给你0或1

if(n == 0){ 
    answer1.setText(correctString); 
    answer2.setText(inCorrectString); 
}else{ 
    answer1.setText(inCorrectString); 
    answer2.setText(correctString); 
}

答案 1 :(得分:0)

试试这个:

Random rand = new Random();
int n = rand.nextInt(2);

if(n == 0){ 
answer1.setText(correctString); 
answer2.setText(inCorrectString); 
}else{ 
answer1.setText(inCorrectString); 
answer2.setText(correctString); 
}

{

@Override
        public void onClick(View v) {
                    answerEvent(answer1.getText().toString());
}
    });
answer2.setOnClickListener(new View.OnClickListener() {
@Override
        public void onClick(View v) {
          answerEvent(answer2.getText().toString());
}
    });
private void answerEvent(String text){
if(text.equals(correctString)))){

Toast bf = Toast.makeText(getApplicationContext(), "Correct",Toast.LENGTH_SHORT);
                 bf.show();
}
            else{
                Intent i = new Intent(getApplicationContext(), TopActivityMath.class);
                startActivity(i);
            }
}