2013-05-06 97 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