简体   繁体   English

获取触发事件的按钮

[英]get the button that fired the event

well at school every week we are making a calculator each week on a different platform (wp7,javascript,iphone,android), today it's android, so i have a method that receives all the keystrokes and depending on the value of the key my class do something to get the value of the button in c# is the sender parameter , in javascript this , in android?? 每周在学校都很好,我们每个星期都在不同的平台(wp7,javascript,iphone,android)上做一个计算器,今天是android,所以我有一种方法可以接收所有击键,并取决于我班上的键的值做一些事情来获取按钮在C#中的值是sender参数,在javascript this中,在android中?

private OnClickListener leclicke= new OnClickListener() {

    public void onClick(View v) {
    //get the id of the button that fired the click event
    //findViewById(R.id.???);
    } };

thank you. 谢谢。

private OnClickListener leclicke= new OnClickListener() {

    public void onClick(View v) {
    //get the id of the button that fired the click event
     int id = v.getId();
    } };

then you must check if this view has an id or not using this 那么您必须检查此视图是否具有ID或不使用此ID

if(id == View.NO_ID){
//this view does not have an id 
}
else{
//the view has an id 
}

调用方法getId()

v.getId();

If you want to use the same OnClickListener for all buttons, then you can do something like this: 如果要对所有按钮使用相同的OnClickListener,则可以执行以下操作:

Button b1 = (Button)findViewById(R.id.button1);
Button b1 = (Button)findViewById(R.id.button2);

private OnClickListener leclicke= new OnClickListener() {

    public void onClick(View v) {

       if(v.equals(b1)) {
         // handle button 1
       } else if(v.equals(b2)) {
         // handle button 2
       } // etc.
    } };

But this is a little clunky. 但这有点笨拙。 Another thing you can do is specify a separate on click method for each method by setting the on click property for the button in the UI Designer, and then declaring that method in your Activity , eg public onClickButton1(View v); 您可以做的另一件事是,通过在UI设计器中为按钮设置public onClickButton1(View v);属性,然后在您的Activity声明该方法,例如, public onClickButton1(View v);为每个方法指定一个单独的on click方法public onClickButton1(View v);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM