Android:如何随机播放onClick按钮的位置?

时间:2014-07-28 11:55:48

标签: android android-layout

在我的应用程序中,用户通过单击2个按钮之一来回答问题。

这些按钮在布局中彼此相邻排列。但是对于每个新问题,我不希望每次两个按钮在同一个地方。即有时按钮1在左侧,有时则在右侧。

我想这样做,以便用户不习惯正确答案/按钮的位置。

我该怎么办?

当前代码

 public class Stroop extends ActionBarActivity implements View.OnClickListener {

        HashMap<String, Integer> colors = new HashMap<>();
        // putting the strings and color vals of the hashmap to an array
        Object stringOnScreen[];
        Object colorsOnScreen[];

        // declare vars
        TextView color;
        Button btn1;
        Button btn2;
        TextView result;

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

            setUpGame();

            btn2.setOnClickListener(this);
            btn1.setOnClickListener(this);

            stringOnScreen = colors.keySet().toArray();
            colorsOnScreen = colors.values().toArray();

            setUpQuestion();

            Log.d("Length", "Length string: " + stringOnScreen.length);

            Log.d("Length", "Length color: " + colorsOnScreen.length);

        }// oncreate end

        public void setUpQuestion() {

            int randString = new Random().nextInt(stringOnScreen.length);
            int randColor = new Random().nextInt(colorsOnScreen.length);

            Log.d("ranString", "randString: " + randString);
            Log.d("rancolor", "randcolor: " + randColor);

            // set the text of the string in textview for user to see
            color.setText("" + stringOnScreen[randString]);
            color.setTextColor((int) colorsOnScreen[randColor]);

            btn1.setText("" + stringOnScreen[randString]); //Set btn1 to the string val

            //Note: uncomment below if the solution under doesnt work
            //btn2.setText("" + colorsOnScreen[randColor].toString()); // set btn2 to the color of the String

            setBtn2Text();

    //      //logic to see if answer is correct, currently commented out to try answer from SO
    //      
    //      if(btn2.getText().equals(convertColorIntToString(color.getCurrentTextColor()))){
    //          
    //          result.setText("Correct");
    //      }
    //      
    //      //trace code
    //      Log.d("colortrace", " " + convertColorIntToString(color.getCurrentTextColor()));

            //trace to check SO method of logic is working
            Log.d("bool", " " + checkForMatchBtn2(btn2));


        }

        public void setUpGame() {

            // setting up the hashmap
            colors.put("Green", Color.GREEN);
            colors.put("Blue", Color.BLUE);
            colors.put("Red", Color.RED);
            colors.put("Yellow", Color.YELLOW);
            colors.put("Black", Color.BLACK);

            // setting up vars
            color = (TextView) findViewById(R.id.tvStroopColor);
            btn1 = (Button) findViewById(R.id.btnStroop1);
            btn2 = (Button) findViewById(R.id.btnStroop2);
            result = (TextView) findViewById(R.id.tvStroopResults);

        }

        public void setBtn2Text(){
            switch(color.getCurrentTextColor()){
                case Color.GREEN:
                    btn2.setText("Green");
                    break;
                case Color.RED:
                    btn2.setText("Red");
                    break;
                case Color.BLUE:
                    btn2.setText("Blue");
                    break;
                case Color.YELLOW:
                    btn2.setText("Yellow");
                    break;
                case Color.BLACK:
                    btn2.setText("Black");
                    break;

            }
        }

        public void onClick(View v){

            if(v.getId() == R.id.btnStroop2){
                if(checkForMatchBtn2(btn2))
                    result.setText("Correct!");
                else
                    result.setText("Wrong!");
            }

            if(v.getId() == R.id.btnStroop1){
                if(checkForMatchBtn1(btn1))
                    result.setText("Correct!");
                else
                    result.setText("Wrong!");
            }
        }

        public boolean checkForMatchBtn2(Button btn2){
            if(color.getCurrentTextColor() == Color.GREEN && btn2.getText().equals("Green"))
                return true;
            else if(color.getCurrentTextColor() == Color.RED && btn2.getText().equals("Red"))
                return true;
            else if(color.getCurrentTextColor() == Color.BLACK && btn2.getText().equals("Black"))
                return true;
            else if(color.getCurrentTextColor() == Color.YELLOW && btn2.getText().equals("Yellow"))
                return true;
            else if(color.getCurrentTextColor() == Color.BLUE && btn2.getText().equals("Blue"))
                return true;
            else 
                return false;
        }

        public boolean checkForMatchBtn1(Button btn1){
            if(color.getCurrentTextColor() == Color.GREEN && btn1.getText().equals("Green"))
                return true;
            else if(color.getCurrentTextColor() == Color.RED && btn1.getText().equals("Red"))
                return true;
            else if(color.getCurrentTextColor() == Color.BLACK && btn1.getText().equals("Black"))
                return true;
            else if(color.getCurrentTextColor() == Color.YELLOW && btn1.getText().equals("Yellow"))
                return true;
            else if(color.getCurrentTextColor() == Color.BLUE && btn1.getText().equals("Blue"))
                return true;
            else 
                return false;
        }

    }

当前布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/tvStroopColor"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:paddingBottom="3dp"
            android:text="meditation "
            android:textSize="40dp" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/btnStroop1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=" "
            android:layout_gravity="center" />

        <Button
            android:id="@+id/btnStroop2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/text_to_set"
            android:text=" "
            android:layout_gravity="center" />
    </LinearLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/tvStroopResults"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:paddingBottom="3dp"
            android:text="  "
            android:textSize="25dp" />

         <TextView
            android:id="@+id/tvStroopScore"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:paddingBottom="3dp"
            android:text=" "
            android:textSize="25dp" 
            android:layout_below="@+id/tvStroopResults"
            />

         <TextView
            android:id="@+id/tvStroopSeeMeditation"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="3dp"
            android:text=" "
            android:textSize="25dp" 
            android:layout_below="@+id/tvStroopScore"
            />

        <TextView
            android:id="@+id/tvStroopSeeAttention"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=" "
            android:textSize="25dp" 
            android:layout_below="@+id/tvStroopSeeMeditation"
            />

        <EditText
        android:id="@+id/etStroopCountdown"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint=" "
        android:layout_below="@+id/tvStroopSeeAttention" >
    </EditText>

    </RelativeLayout>

</LinearLayout>

尝试解决方案:

private Random random = new Random();

    public void setUpGame() {

            // setting up the hashmap
            colors.put("Green", Color.GREEN);
            colors.put("Blue", Color.BLUE);
            colors.put("Red", Color.RED);
            colors.put("Yellow", Color.YELLOW);
            colors.put("Black", Color.BLACK);

            // setting up vars
            color = (TextView) findViewById(R.id.tvStroopColor);

    //      btn1 = (Button) findViewById(R.id.btnStroop1);
    //      btn2 = (Button) findViewById(R.id.btnStroop2);
    //      
            result = (TextView) findViewById(R.id.tvStroopResults);
            showScore = (TextView) findViewById(R.id.tvStroopScore);
            seeMed = (TextView) findViewById(R.id.tvStroopSeeMeditation);
            seeAtt = (TextView) findViewById(R.id.tvStroopSeeAttention);
            tenSecs= MediaPlayer.create(Stroop.this, R.raw.tenseconds);
            countdown= (EditText) findViewById(R.id.etStroopCountdown);


            int[] buttons = new int[]{R.id.btnStroop1, R.id.btnStroop2};
            int first = random.nextInt(1);
            btn1 = (Button) findViewById(buttons[first]);
            btn2 = (Button) findViewById(buttons[1-first]);


        }

编辑2:

public void onClick(View v){

       // if(v.getId() == R.id.btnStroop2){
            if(checkForMatchBtn2((Button) v)){

                result.setText("Correct!");
                result.setTextColor(Color.GREEN);
                score++;
            }
            else{
                  result.setText("Wrong!");
                  result.setTextColor(Color.RED);

            }

            //set up the question again
            setUpQuestion();

       // }

       // if(v.getId() == R.id.btnStroop1){
            if(checkForMatchBtn1((Button) v)){


                result.setText("Correct!");
                result.setTextColor(Color.GREEN);
                score++;
            }
            else{

                result.setText("Wrong!");
                result.setTextColor(Color.RED);
            }

            //set up the question again
            setUpQuestion();
       // }
    }//end of onclick

CURRENT ONCLICK METHOD:

//THIS MAY NEED TO BE CHANGED!!
    public void onClick(View v) {

        if (v.getId() == R.id.btnStroop2) {
            if (checkForMatchBtn2((Button) v)) {

                result.setText("Correct!");
                result.setTextColor(Color.GREEN);
                score++;
            } else {
                result.setText("Wrong!");
                result.setTextColor(Color.RED);

            }

            // set up the question again
            setUpQuestion();

        }

        if (v.getId() == R.id.btnStroop1) {
            if (checkForMatchBtn1((Button) v)) {

                result.setText("Correct!");
                result.setTextColor(Color.GREEN);
                score++;
            } else {

                result.setText("Wrong!");
                result.setTextColor(Color.RED);
            }

            // set up the question again
            setUpQuestion();
        }
    }// end of onclick

最近编辑:

public class Stroop extends Activity implements View.OnClickListener {

    HashMap<String, Integer> colors = new HashMap<>();
    // putting the strings and color vals of the hashmap to an array
    Object stringOnScreen[];
    Object colorsOnScreen[];

    // declare vars
    TextView color;
    Button btn1;
    Button btn2;
    TextView result;
    TextView showScore;
    TextView seeMed;
    TextView seeAtt;

    int score=0;
    MediaPlayer tenSecs;
    // vars related to neurosky

    BluetoothAdapter bluetoothAdapter;
    TGDevice device;
    TGEegPower eegPower;
    final boolean rawEnabled = true;

    List<Integer> meditationValues = new ArrayList<Integer>();
    int averageMedLevel;
    int totalofMedLevels;
    int medCount = 0;
    int medMax;

    // for attention
    List<Integer> AttentionValues = new ArrayList<Integer>();
    int averageAttLevel;
    int totalofAttLevels;
    int attCount = 0;
    int attMax;

    // used for displaying seconds left
    EditText countdown;

    // in relation to saving values to file
    List<TGEegPower> medPoints = new ArrayList<TGEegPower>();
    File dir;
    int medValueToWrite;
    int attValueToWrite;

    // in relation to the results display in next activity
    ArrayList<Score> singleScore;
    Score single;

    private Random random = new Random();




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

        setUpGame();

        stringOnScreen = colors.keySet().toArray();
        colorsOnScreen = colors.values().toArray();

        setUpQuestion();

        btn2.setOnClickListener(this);
        btn1.setOnClickListener(this);




    }// oncreate end

    public void setUpQuestion() {

        int[] buttons = new int[]{R.id.btnStroop1, R.id.btnStroop2};
        int first = random.nextInt(2);

        btn1 = (Button) findViewById(buttons[first]); //btnstroop1 or btnstroop2
        btn2 = (Button) findViewById(buttons[1-first]); //the opposite btn

        int randString = new Random().nextInt(stringOnScreen.length);
        int randColor = new Random().nextInt(colorsOnScreen.length);

        // set the text of the string in textview for user to see
        color.setText("" + stringOnScreen[randString]);
        color.setTextColor((int) colorsOnScreen[randColor]);


        btn1.setText("" + stringOnScreen[randString]); //Set btn1 to the string val

        setBtn2Text();

        showScore.setText("Score= " + score);

    }

    public void setUpGame() {

        // setting up the hashmap
        colors.put("Green", Color.GREEN);
        colors.put("Blue", Color.BLUE);
        colors.put("Red", Color.RED);
        colors.put("Yellow", Color.YELLOW);
        colors.put("Black", Color.BLACK);

        // setting up vars
        color = (TextView) findViewById(R.id.tvStroopColor);
        result = (TextView) findViewById(R.id.tvStroopResults);
        showScore = (TextView) findViewById(R.id.tvStroopScore);
        seeMed = (TextView) findViewById(R.id.tvStroopSeeMeditation);
        seeAtt = (TextView) findViewById(R.id.tvStroopSeeAttention);
        tenSecs= MediaPlayer.create(Stroop.this, R.raw.tenseconds);
        countdown= (EditText) findViewById(R.id.etStroopCountdown);

    }

    public void setBtn2Text(){
        switch(color.getCurrentTextColor()){
            case Color.GREEN:
                btn2.setText("Green");
                break;
            case Color.RED:
                btn2.setText("Red");
                break;
            case Color.BLUE:
                btn2.setText("Blue");
                break;
            case Color.YELLOW:
                btn2.setText("Yellow");
                break;
            case Color.BLACK:
                btn2.setText("Black");
                break;

        }
    }

    public void onClick(View v) {

         if(checkForMatchBtn2((Button) v)){

                result.setText("Correct!");
                result.setTextColor(Color.GREEN);
                score++;
         }else{
                result.setText("Wrong!");
                result.setTextColor(Color.RED);
            }

        setUpQuestion();
    }

    public boolean checkForMatchBtn2(Button btn2){
        if(color.getCurrentTextColor() == Color.GREEN && btn2.getText().equals("Green"))
            return true;
        else if(color.getCurrentTextColor() == Color.RED && btn2.getText().equals("Red"))
            return true;
        else if(color.getCurrentTextColor() == Color.BLACK && btn2.getText().equals("Black"))
            return true;
        else if(color.getCurrentTextColor() == Color.YELLOW && btn2.getText().equals("Yellow"))
            return true;
        else if(color.getCurrentTextColor() == Color.BLUE && btn2.getText().equals("Blue"))
            return true;
        else 
            return false;
    }

    public boolean checkForMatchBtn1(Button btn1){
        if(color.getCurrentTextColor() == Color.GREEN && btn1.getText().equals("Green"))
            return true;
        else if(color.getCurrentTextColor() == Color.RED && btn1.getText().equals("Red"))
            return true;
        else if(color.getCurrentTextColor() == Color.BLACK && btn1.getText().equals("Black"))
            return true;
        else if(color.getCurrentTextColor() == Color.YELLOW && btn1.getText().equals("Yellow"))
            return true;
        else if(color.getCurrentTextColor() == Color.BLUE && btn1.getText().equals("Blue"))
            return true;
        else 
            return false;
    }
}

2 个答案:

答案 0 :(得分:1)

private Random random = new Random();

然后当你找到按钮时:

btn1 = (Button) findViewById(R.id.btnStroop1);
btn2 = (Button) findViewById(R.id.btnStroop2);

随机找到它们:

int[] buttons = new int[]{R.id.btnStroop1, R.id.btnStroop2};
int first = random.nextInt(2); //0 or 1
btn1 = (Button) findViewById(buttons[first]);   //btnStroop1 or btnStroop2
btn2 = (Button) findViewById(buttons[1-first]); //the opposite button

但你也需要这样做:

public void onClick(View v){
  if(checkForMatchBtn2((Button) v))
    result.setText("Correct!");
  else
    result.setText("Wrong!");
}

因为现有代码仍将btn1btnStroop1等链接起来

答案 1 :(得分:1)

不是在布局文件中定义按钮,而是动态地将按钮添加到LinearLayout。

  1. 为LineaLayout设置@ + id。
  2. 获取LinearLayout并以随机顺序动态添加按钮。
  3. LinearLayout layout = (LinearLayout)view.findViewById(R.id.your_linear_layout);    
    Button btn = new Button(this);  
    btn.setText("Yes"); 
    //TODO Set Button layout params here
    layout.addView(btn);
    

    同样添加另一个Button并设置onClick侦听器。

    生成随机数,并根据该设置以不同顺序设置“是”或“否”按钮。

    Random randomGenerator = new Random();
    
    randomNumber = randomGenerator.nextInt(1000);
    
    if(randomNumber % 2 == 0){
    
       add Yes button;
    
       add No button;
    
    }else{
    
       add No buttton;
    
       add Yes button;
    
    }
    

    希望它有所帮助。