【Button】按鈕onTouch事件監聽
阿新 • • 發佈:2019-02-18
程式碼實現的功能是使得一個按鈕在按下的實現顯示黃色圖安,擡起的時候的顯示綠色圖案。
然後圖案自己設定形狀。當然還可以缺一角什麼的。
為Button繫結 OnTouchListener 監聽器。
程式碼對應有click時間,對比看看這倆個時間的區別
1.public class AppMain extends Activity{ 2. 3. private Button mButton; 4. 5. /** Called when the activity is first created. */ 6. public void onCreate(Bundle savedInstanceState) { 7. super.onCreate(savedInstanceState); 8. setContentView(R.layout.main); 9. 10. ButtonListener b = new ButtonListener(); 11. mButton = (Button)findViewById(R.id.button1); 12. mButton.setOnClickListener(b); 13. mButton.setOnTouchListener(b); 14. mButton.setBackgroundResource(R.drawable.green); 15. 16. } 17. 18. class ButtonListener implements OnClickListener, OnTouchListener{ 19. 20. public void onClick(View v) { 21. if(v.getId() == R.id.button1){ 22. Log.d("test", "cansal button ---> click"); 23. } 24. } 25. 26. public boolean onTouch(View v, MotionEvent event) { 27. if(v.getId() == R.id.button1){ 28. if(event.getAction() == MotionEvent.ACTION_UP){ 29. Log.d("test", "cansal button ---> cancel"); 30. mButton.setBackgroundResource(R.drawable.green); 31. } 32. if(event.getAction() == MotionEvent.ACTION_DOWN){ 33. Log.d("test", "cansal button ---> down"); 34. mButton.setBackgroundResource(R.drawable.yellow); 35. } 36. } 37. return false; 38. } 39. 40. } 41.}