android 組件內部實現觸摸事件,更改背景

來源:互聯網
上載者:User

當我們需要實現觸摸事件的時候,通常就會想到OnTouchEvent這個方法,它能夠擷取觸摸點的座標,而組件同樣也有這樣的一個功能,使用這個功能,可以實現組件在父布局介面上移動,縮放,更改背景圖片。這裡通過一個小例子來實現利用組件的onTouchEvent事件實現點擊組件左半部分更改左邊圖片,點擊組件右半部分更改右邊圖片。

if (v == CamMove_UD_Btn) {if (event.getAction() == MotionEvent.ACTION_DOWN) {if (event.getX() <= btn_in_bottom_width_center) { //這個是組件寬度的一半CamMove_UD_Btn.setBackgroundResource(R.drawable.cam_up);}else {CamMove_UD_Btn.setBackgroundResource(R.drawable.cam_down);}CamMove_UD_Btn_Click = true;//使用這個變數的目的就是:有時手指從水平位置滑動到組件到,沒有檢測到Down事件,但是鬆開手後就會檢測到UP}else if (CamMove_UD_Btn_Click && event.getAction() == MotionEvent.ACTION_UP) {CamMove_UD_Btn.setBackgroundResource(R.drawable.cam_off);CamMove_UD_Btn_Click = false;}}

其實思路是很簡單的。擷取手電級的位置,如果組件是橫向的,擷取X座標,如果小於組件的一半則認為是左邊,如果大於一般則認為是右邊。

下面是對於組件自己的移動

imagebutton.setOnTouchListener(new OnTouchListener() {              int[] postion = new int[] { 0, 0 };              @Override              public boolean onTouch(View v, MotionEvent event) {                  int x = (int) event.getRawX();                  int y = (int) event.getRawY();                  int left = v.getLeft();                  int top = v.getTop();                  switch (event.getAction()) {                  case MotionEvent.ACTION_DOWN:                      postion[0] = (int) event.getX();                      postion[1] = y - v.getTop();                      break;                    case MotionEvent.ACTION_MOVE:                      v.layout(x - postion[0], y - postion[1], x + 1024                              - postion[0], y - postion[1] + 768);                      v.postInvalidate();                      default:break;                  }                  return false;              }            });  

下面是布局的移動

            x=x+10;              y=y+10;              LayoutParams layoutParams=mIconPinpu.getLayoutParams();  //擷取布局的布局參數            layoutParams.height=x;              layoutParams.width=y;              mIconPinpu.setLayoutParams(layoutParams);  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.