歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android Button 的按下和抬起事件監聽

Android Button 的按下和抬起事件監聽

日期:2017/3/1 11:10:35   编辑:Linux編程

代碼實現的功能是使得一個按鈕在按下的實現顯示光色圖安,抬起的時候的顯示黃色圖案。

然後圖案自己設置形狀。當然還可以缺一角什麼的。

為Button綁定 OnTouchListener 監聽器。

  1. public class AppMain extends Activity{
  2. private Button mButton;
  3. /** Called when the activity is first created. */
  4. public void onCreate(Bundle savedInstanceState) {
  5. super.onCreate(savedInstanceState);
  6. setContentView(R.layout.main);
  7. ButtonListener b = new ButtonListener();
  8. mButton = (Button)findViewById(R.id.button1);
  9. mButton.setOnClickListener(b);
  10. mButton.setOnTouchListener(b);
  11. mButton.setBackgroundResource(R.drawable.green);
  12. }
  13. class ButtonListener implements OnClickListener, OnTouchListener{
  14. public void onClick(View v) {
  15. if(v.getId() == R.id.button1){
  16. Log.d("test", "cansal button ---> click");
  17. }
  18. }
  19. public boolean onTouch(View v, MotionEvent event) {
  20. if(v.getId() == R.id.button1){
  21. if(event.getAction() == MotionEvent.ACTION_UP){
  22. Log.d("test", "cansal button ---> cancel");
  23. mButton.setBackgroundResource(R.drawable.green);
  24. }
  25. if(event.getAction() == MotionEvent.ACTION_DOWN){
  26. Log.d("test", "cansal button ---> down");
  27. mButton.setBackgroundResource(R.drawable.yellow);
  28. }
  29. }
  30. return false;
  31. }
  32. }
  33. }
Copyright © Linux教程網 All Rights Reserved