如何监听特定按钮按下以及家庭视图用户交互?

时间:2010-08-08 08:02:37

标签: java android

我的应用程序侦听来自触摸屏和按钮的用户输入,但我想听取主屏幕视图中特定项目的交互。因此,例如,我需要听取用户点击菜单按钮,然后生成输出。有没有我可以通过onClick()类传递的参数?或者我需要采取另一种方式?

1 个答案:

答案 0 :(得分:0)

public class Mtest extends Activity {
  Button b1;
  Button b2;
  public void onCreate(Bundle savedInstanceState) {
    ...
    b1 = (Button) findViewById(R.id.b1);
    b2 = (Button) findViewById(R.id.b2);
    b1.setOnClickListener(myhandler1);
    b2.setOnClickListener(myhandler2);
    ...
  }
  View.OnClickListener myhandler1 = new View.OnClickListener() {
    public void onClick(View v) {
      // it was the 1st button
    }
  };
  View.OnClickListener myhandler2 = new View.OnClickListener() {
    public void onClick(View v) {
      // it was the 2nd button
    }
  };
}

或者,如果您只使用一个clicklistener,则可以执行以下操作:

View.OnClickListener myOnlyhandler = new View.OnClickListener() {
  public void onClick(View v) {
      switch(v.getId()) {
        case R.id.b1:
          // it was the first button
          break;
        case R.id.b2:
          // it was the second button
          break;
      }
  }
}