0

我想知道是否有一种与该方法类似的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
                }
        });
    }
}
4

2 回答 2

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;
}      
   }
}
于 2012-07-30T18:08:15.530 回答
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);
于 2012-07-30T18:14:36.237 回答