以下代碼為利用插入OnTouchListener,達到以觸控方式移動物件
public class MainActivity extends Activity implements OnTouchListener{
ImageView imageView1;
Point touch_xy;
private int tvWidth = LayoutParams.WRAP_CONTENT;
private int tvHeight = LayoutParams.WRAP_CONTENT;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialization();
}
public void initialization(){
imageView1 = (ImageView)findViewById(R.id.image1);
imageView1.setOnTouchListener(this);
touch_xy = new Point();
}
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO 自动生成的方法存根
// 以 event.getAction獲得當前觸控事件。ACTION_DOWN為按下,ACTION_MOVE為移動,ACTION_UP為放開
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
Log.i("touch", "down");
// 一開始按下去的位置
touch_xy.x = (int)event.getRawX()-30;
touch_xy.y = (int) event.getRawY()-100;
break;
case MotionEvent.ACTION_MOVE:
// 利用layout佈局重新定義圖片位置
v.setLayoutParams( new AbsoluteLayout.LayoutParams(
tvWidth
, tvHeight
, touch_xy.x
, touch_xy.y
));
// 移動中再次取得當前觸控按位置
touch_xy.x = (int)event.getRawX()-30;
touch_xy.y = (int) event.getRawY()-100;
break;
case MotionEvent.ACTION_UP:
Log.i("touch", "up");
break;
}
return true;
}
請先 登入 以發表留言。