Android触控拖动事件处理

触控拖动屏幕事件一般情况下是重载onTouchEvent函数 实现方法如下

 

ContractedBlock.gif ExpandedBlockStart.gif 代码
 
   
/** mainView的坐标 */
private float x, y;
/** 触屏事件处理 */
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
this .x = x;
this .y = y;
case MotionEvent.ACTION_MOVE:
mainView.layout((
int )(x - this .x), ( int )(y - this .y), ( int )(x + mainView.getWidth()
- this .x), ( int )(y - this .y + mainView.getHeight()));

break ;
case MotionEvent.ACTION_UP:
if ((Math.abs( this .y - y) < 10 ))
{
if (x - this .x > 30 )
{
MessageBox(
" 向右移动 " );
}
else if (x - this .x < - 30 )
{
MessageBox(
" 向左移动 " );
}
}
break ;
}
mainView.postInvalidate();
return super .onTouchEvent(event);
}

处理控件拖动事件跟上边类似 可添加一个OnTouchListener到控件上

下边展示一个对Button按钮的拖动

 

ContractedBlock.gif ExpandedBlockStart.gif 代码
 
   

final Button btn = (Button) findViewById(R.id.btn_hello);

btn.setOnTouchListener(
new OnTouchListener() {
int [] temp = new int [] { 0 , 0 };

public boolean onTouch(View v, MotionEvent event) {

int eventaction = event.getAction();
Log.i(
" &&& " , " onTouchEvent: " + eventaction);

int x = ( int ) event.getRawX();
int y = ( int ) event.getRawY();

switch (eventaction) {

case MotionEvent.ACTION_DOWN: // touch down so check if the
temp[ 0 ] = ( int ) event.getX();
temp[
1 ] = y - v.getTop();
break ;

case MotionEvent.ACTION_MOVE: // touch drag with the ball
v.layout(x - temp[ 0 ], y - temp[ 1 ], x + v.getWidth()
- temp[ 0 ], y - temp[ 1 ] + v.getHeight());

v.postInvalidate();
break ;

case MotionEvent.ACTION_UP:
break ;
}

return false ;
}

});

 

拖动事件主要就是在touch事件的envent中处理按下 移动 和 松开

转载于:https://www.cnblogs.com/xingyan/archive/2010/08/18/1802200.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值