View.getId和R.id.viewLabel返回不同的值 [英] View.getId and R.id.viewLabel return different values

查看:1160
本文介绍了View.getId和R.id.viewLabel返回不同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有一个这样的方法到我的活动,并将其设置为的onClick 场不同的按钮转换成XML:

Let's say I have a method like this into my activity, and set it as onClick field of different buttons into xml:

public void onButtonPressedFromView(View button) {
   switch(button.getId()) {
   case (R.id.button1) :
      //do something
      break;
   case (R.id.button2) :
      //do something different
      break;
   default :
      //default action
      break;
   }
}

它出来,如果​​我preSS比如按钮1,用 button.getId()获得的ID总是更大的1比获得的ID R.id.button1 。这是很容易解决的,我只是改变了我的code到

It comes out that, if I press for instance button1, the id obtained with button.getId() is always bigger of 1 than the id obtained with R.id.button1. It's quite easy to solve, I just changed my code into

开关(button.getId() - 1)

但我不喜欢它,并想了解获得视图的id的这两种方式之间的区别。

but I don't like it, and would like to understand the difference between these two ways of obtaining the id of a view.

推荐答案

您应该知道按钮比较到presses。

You should be comparing known buttons to the presses.

onCreate(...) {
    ...
   Button myButton1 = (Button)findViewById(R.id.somebutton);
   Button myButton2 =....
}



public void onButtonPressedFromView(View button) {
   switch(button.getId()) {
   case (myButton1.getId()) :
      //do something
      break;
   case (myButton2.getId()) :
      //do something different
      break;
   default :
      //default action
      break;
   }
}

不承担== myButton的按钮,它是非常重要的。例如,如果在一个ListView使用一个按钮,它可能将有几个实例,因此可以仅是可比由的getId()属性

It is important to not assume myButton == button. For instance, if you use a button in a ListView it will likely have several instances and can thus only be comparable by the getId() property.

这篇关于View.getId和R.id.viewLabel返回不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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