2010-11-14 53 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應用程序即將推出!