2012-07-30 80 views
0

我想知道是否有一種方法的作用類似於onOptionsItemSelected方法,但是監聽所有在UI中實現的按鈕,而是監聽Options Menu項目。作爲類似於OnOptionsItemSelected方法的Button監聽器的方法

onOptionsItemSelected()方法:

public boolean onOptionsItemSelected(MenuItem item) { 
    switch(item.getItemId()) { 
     case R.id.item1: 
      if(currentPlayer == 1) {return true;} 
       updateUI(1); 
      return true; 
     case R.id.item2: 
      if(currentPlayer == 2) {return true;} 
       updateUI(2); 
      return true; 
     case R.id.item3: 
      if(currentPlayer == 3) {return true;} 
       updateUI(3); 
      return true; 
     case R.id.item4: 
      if(currentPlayer == 4) {return true;} 
       updateUI(4); 
      return true; 
     default: 
      return super.onContextItemSelected(item); 
    } 
} 

現在,我堅持使用這種方法爲每一個按鈕,我有太多的。如果我能找到一種像上面那樣工作的方法,它將會更加清潔。

public class MyActivity extends Activity { 
    protected void onCreate(Bundle icicle) { 
     super.onCreate(icicle); 

     setContentView(R.layout.content_layout_id); 

     final Button button = (Button) findViewById(R.id.button_id); 
     button.setOnClickListener(new View.OnClickListener() { 
       public void onClick(View v) { 
        // Perform action on click 
       } 
     }); 
    } 
} 

回答

2
public class MyActivity extends Activity implements OnClickListener{ 
protected void onCreate(Bundle icicle) { 
    super.onCreate(icicle); 
    setContentView(R.layout.content_layout_id); 

    final Button button = (Button) findViewById(R.id.button_id); 
    button.setOnClickListener(this); 

    //asign for othe button if its btn1,btn2,btn3 
    btn1.setOnClickListener(this); 
    btn2.setOnClickListener(this); 
    btn3.setOnClickListener(this); 


} 

public void onClick(View v) { 
switch(v.getId()) { 
case R.id.button_id: 
    //put code here for button_id 
break; 

case R.id.button_id_1: 
    break; 

default: 
    break; 
}  
    } 
} 
1
View.OnClickListsner buttonListener = new View.OnClickListener() { 
@Override 
publiv oid onClick(View view) { 
Swicth(view.getId()) { 
your stuff like in your question 
} 
} 
} 

而且不要忘記這個listsner添加到每個按鈕像這樣:

butoon1.setOnClickListener(buttonListsner); 
button2.setOnClickListsner(buttonListsner); 
相關問題