2013-04-29 1 views
3

정수 0,1,2,3,4가있는 목록이 있습니다. 그리고 나서 3 단계로 button1과 관련된 첫 번째 객체, button2와 같은 두 번째 객체 등으로 Button을 초기화하려고합니다. 수동으로 수행하면 작동하지만 동적으로 해결하고 싶습니다.이 랜덤 버튼 구현을 동적으로 해결하는 방법

List<Integer> objects = new ArrayList<Integer>(); 
      objects.add(0); 
      objects.add(1); 
      objects.add(2); 
      objects.add(3); 
      objects.add(4); 

     // Shuffle the collection 
    Collections.shuffle(objects); 

//this is not working here, but it should reflect what i am trying to achieve here 
// --> 
    for (int i = 0; i<objects.size(); i++) { 
     Button button**i** = (Button)findViewById(R.id.button**i**); 
     button**i**.setText(objects.get(i).toString()); 
    } 

미리 감사드립니다. 어떤 도움을 주셔서 감사합니다 (올바른 방향으로 코를 파고)

+0

: 이것처럼

? 'R.id.button ** i **'에 오류가 있습니까? –

+0

글쎄, 당신은 자바에서 초기화에 변수 variablename stringbuild 수 없습니다. – bofredo

+2

java에서는 허용하지 않습니다. 당신은 접근법 @fonZ 대답을 사용할 수 있습니다 ... –

답변

4

버튼 목록을 뒤섞어서 해결할 수 있습니다. int로 iterating 할 때 shuffled 목록의 인덱스 역할을 할 수 있습니다. 무엇을 작동하지

List<Button> buttons = new ArrayList<Button>(); 
buttons.add((Button)findViewById(R.id.button0)); 
buttons.add((Button)findViewById(R.id.button1)); 
buttons.add((Button)findViewById(R.id.button2)); 
buttons.add((Button)findViewById(R.id.button3)); 
buttons.add((Button)findViewById(R.id.button4)); 

Collections.shuffle(buttons); 

for (int i = 0, s = 4; i < s; i++) { 
    buttons.get(i).setText("" + i); 
} 
+0

"at"- 방법

+0

변경된 내용 : – fonZ

+1

첫 번째 줄을 주목하면 가치가 있습니다. 목록 indexes = Arrays.asList (new int [] {0,1,2,3,4}); ' –