2010-11-14 55 views
1

在我的布局xml文件中,我已将Button元素的android:onClick属性设置为我的活动中的函数。所以当我点击按钮时,函数被视为一个参数。该视图参数中是否有该按钮的ID被点击的信息?我试图找出是否必须为每个元素都有一个onClick函数,或者如果我可以使用一个函数并根据被单击元素的id切换。OnClick侦听器 - 所有点击的函数

+0

尝试使用getId() - 方法? – Mikpa 2010-11-14 13:25:32

回答

3
switch (v.getID) { 
case R.id.A: 
..... 
} 
0

喔应用有答案没事......只是throughness我有一些像这样... 大小写敏感的东西....有趣的如何的getID将无法正常工作,而一个的getId将是金...有趣的是,编译器不能做一个“马虎检查”,并纠正这种情况下的问题。

像这样

View myButton = findViewById(R.id.mybutton); 
    myButton.setOnClickListener(this); 
    View myOtherButton = findViewById(R.id.myotherbutton); 
     myOtherButton.setOnClickListener(this); 
public void onClick(View v) { 
      switch (v.getId()) { 
      case R.id.mybutton: 
           //Do something related to the mybutton click 

      break; 
     case R.id.myotherbutton:  
           //Do something related to the myotherbutton click 

      break; 
     //chain all Resource ID's here like above.... 
            } 
} 

还必须不要忘记设置一个的onclick侦听器开关或案前的每个点击事件将永远不会得到解决....

//喔豪。 8cupsaday android应用程序即将推出!