2013-05-06 2 views
0

내 자신의 연습을 위해 인스턴스 필드에 3 개의 버튼 배열을 만들고 각 버튼이 BackGround Color를 변경할 수있는 setOnClickListeners를 갖고 싶습니다.버튼 배열을위한 리스너 (들)

  public class MainActivity extends Activity { 

     Button b = {(Button)findViewById(R.id.button1), 
        (Button)findViewById(R.id.button2), 
        (Button)findViewById(R.id.button3),}; 

    TextView tv; 

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

    tv = (TextView) findViewById(R.id.textView1); 

    for(int i=0; i < b.length;i++){ 





    b[i].setOnClickListener(new OnClickListener() { 

    @Override 
     public void onClick(View v) { 

      if(butt[0].isPressed()){ 
     tv.setBackgroundColor(Color.BLACK); 
      } 


      if(b[1].isPressed()){ 
       tv.setBackgroundColor(Color.BLUE); 
       } 
      if(b[2].isPressed()){ 
       tv.setBackgroundColor(Color.RED); 
       } 

       } 
       }); 


       } 
      } 

     } 
+0

아래 뭔가를 수행하여 switch으로 클릭했다. 따라서 해당 버튼을 누를 때 특정 버튼을 클릭 할 때 실행할 코드 만 * 포함하십시오. – christopher

+0

'Button b = ...'는'Button [] b = ...'여야합니다. – drunkenRabbit

답변

0

당신은 당신의 Buttons에 대한 Array를 선언하지 않는 : 사람 View.Can 텍스트가 바로 direction.Here으로 나를 인도 해주십시오 나의 코드입니다. 나는 이것이 어떻게 할 것인지 확실하지 않다거나 심지어 컴파일 만한다면 나 또한 그렇게

Button b = {(Button)findViewById(R.id.button1), 
       (Button)findViewById(R.id.button2), 
       (Button)findViewById(R.id.button3),}; 

변경 그것에

Button[] b = {(Button)findViewById(R.id.button1), 
       (Button)findViewById(R.id.button2), 
       (Button)findViewById(R.id.button3),}; 

생각하지 것이다,이 코드는 setcontentView() 또는 후 가야 Buttons이 (가) layout에 있고, layout이 존재하지 않으면 setContentView()으로 전화를 걸기 전까지는 NPE이됩니다.

당신은 선언 할 수 ArrayonCreate() 전에 그러나 당신이 팽창 할 때까지 당신이 그들을 초기화 할 수 없습니다 당신의 layout

@pragnani는 그의 대답 I를 삭제하기 때문에 그래서 당신은이

public class MainActivity extends Activity { 

    Button[] b = new Button[3]; //initialize as an array 

TextView tv; 

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

b = {(Button)findViewById(R.id.button1), 
      (Button)findViewById(R.id.button2), 
      (Button)findViewById(R.id.button3),}; //add buttons AFTER calling setContentView() 
... 

편집과 같은 작업을 수행 할 수 있습니다 조금이라도 편집하면 좋은 아이디어입니다

을 선택하면 논리를 단순화 할 수 있습니다당신은 버튼에 대한 리스너를 설정하는 당신의 for loop

b[i].setOnClickListener(new OnClickListener() { 

@Override 
    public void onClick(View v) { /v is the button that was clicked 

     switch (v.getId()) //so we get its id here 
     { 
      case (R.id.button1): 
      tv.setBackgroundColor(Color.BLACK); 
      break; 
      case (R.id.button2): 
      tv.setBackgroundColor(Color.BLUE); 
      break; 
      case (R.id.button3): 
      tv.setBackgroundColor(Color.RED); 
      break; 
     } 
+0

@ chris-cooney, 정말 고마워요. – HRo

+0

@HRo 좀 더 쉽게 답변을 편집했습니다 ... pragnani의 대답에 따르면 그는 – codeMagic

+0

@ codeMagic-> thanks를 삭제했습니다. – HRo