充当Button侦听器的方法,类似于OnOptionsItemSelected方法

时间:2012-07-30 18:05:36

标签: android button listener

我想知道是否存在类似于onOptionsItemSelected方法的方法,而是侦听选项菜单项,它会侦听UI中实现的所有按钮。

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 个答案:

答案 0 :(得分: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 :(得分:1)

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

并且不要忘记将此侦听器添加到每个按钮中:

butoon1.setOnClickListener(buttonListsner);
button2.setOnClickListsner(buttonListsner);