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

查看:15
本文介绍了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天全站免登陆