2017-07-27 76 views
0

我想洗牌android中的單選按鈕,這裏是代碼我到現在爲止所做的,但隨着我進一步進行,我沒有得到什麼應該是代碼或如何做到這一點。在android中的單選按鈕洗牌

如果我錯了,請糾正,或者做一些愚蠢的錯誤,因爲我是新手。

ArrayList<RadioButton> arrayText = new ArrayList<>(); 

arrayText.add(ropt0); 
arrayText.add(ropt1); 
arrayText.add(ropt2); 
arrayText.add(ranswer); 

Collections.shuffle(arrayText); 

我沒有得到什麼後年Collections.shuffle(arrayText); 應該是代碼

請建議

回答

0

我覺得你不太明白你在做什麼?你想要什麼。在您的代碼中,您只需將所有RadioButtons添加到ArrayList,然後將此清單洗牌。

ArrayList<Stirng> list = new ArrayList<String>(); 
list.add("a1"); 
list.add("a2"); 

Collections.shuffle(list); 

你看,這不是在任何方面與UI:因爲這是一樣的。如果你想在洗牌UI(用戶因此將看到它)按鈕,你有兩種方式:

  1. 創建並添加代碼的單選按鈕。鑑於XML文件中定義了一些RadioGroup,然後創建並添加RadioButton小號

    RadioGroup lay = (RadioGroup) findViewById(R.id.my_radio_group); 
    List<RadioButton> buttons = new ArrayList<>(); 
    RadioButton rb1 = new RadioButton(this); 
    RadioButton rb2 = new RadioButton(this); 
    buttons.add(rb1); 
    buttons.add(rb2); 
    Collections.shuffle(buttons); 
    for(RadioButton rb: 
        buttons){ 
        lay.addView(rb,new RadioGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); 
    } 
    
  2. 洗牌只是一個右按鈕的位置。在XML中創建N按鈕。然後在你的代碼中設置所有的文本,這樣你就可以決定哪個按鈕是正確的。

    List<String> answers = new ArrayList<>(4); // 4 - button number 
    //Fill the list here 
    int rightAnswerPosition = ...; //Decide it when you fill your list 
    rb1.setText(answers.get(0)); 
    //.. and so on