Droid:如何从XML中描述的onClick方法获取按钮ID? [英] Droid: How to get button id from onClick method described in XML?

查看:88
本文介绍了Droid:如何从XML中描述的onClick方法获取按钮ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

按照开发指南,我可以在XML中使用按钮添加方法.这将在我的活动中调用"buttonPress"方法.如果我对多个按钮应用相同的方法,该如何确定已单击的按钮的身份?

Following the dev guide, I can add a method to a button using in the XML. This calls the 'buttonPress' method in my activity. If I apply the same method to multiple buttons, how can I determine the identity of the button that has been clicked?

推荐答案

使用getId()方法.它会返回int id,您可以将其与资源中的id进行比较.

Use getId() method. It returnes the int id that you can compare to the id from resources.

使用这样的switch语句非常方便:

It is very convenient to use switch statement like this:

public void buttonPress(View v) {
    switch (v.getId()) {
        case R.id.button_one:
            // do something
            break;
        case R.id.button_two:
            // do something else
            break;
        case R.id.button_three:
            // i'm lazy, do nothing
            break;
    }
}

这篇关于Droid:如何从XML中描述的onClick方法获取按钮ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆