2013-05-06 258 views
0

對於我自己的練習,我在實例字段中創建了一個3個按鈕的數組,並且我希望所有這些按鈕都具有setOnClickListeners,它允許每個按鈕更改一個按鈕的BackGround Color文字View.Can任何人請指導我朝着正確的direction.Here是我的代碼:按鈕陣列的監聽器

  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 2013-05-06 15:52:30

+0

'按鈕b = ...'應該是按鈕[] b = ...' – drunkenRabbit 2013-05-06 15:53:50

回答

0

你是不是宣佈你ButtonsArray。我不知道這是什麼會做,或者如果它甚至會編譯,但我不這麼認爲

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()或者你去後將獲得NPE,因爲您的Buttons存在於您的layout中,並且您的layout不存在,除非您通過致電setContentView()來誇大它。

你可以聲明ArrayonCreate(),但要等到擡高你不能對它們進行初始化您layout

所以,你可以做這樣的事情

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() 
... 

編輯自@pragnani刪除他的回答我將編輯一點,這是一個好主意

你可以簡化你的邏輯,通過選擇哪個Button被做在你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 2013-05-06 16:10:09

+0

@HRo我已經編輯了一些更多的答案,這將使它更容易...每個pragnani的答案,他刪除 – codeMagic 2013-05-06 16:27:08

+0

@ codeMagic->謝謝。 – HRo 2013-05-11 07:13:33