以下代碼為利用插入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;
}

初學者日記 發表在 痞客邦 留言(0) 人氣()


在程式初期未設定時,螢幕上方總是有礙眼的邊框。

 
 

初學者日記 發表在 痞客邦 留言(0) 人氣()

1
Blog Stats
⚠️

成人內容提醒

本部落格內容僅限年滿十八歲者瀏覽。
若您未滿十八歲,請立即離開。

已滿十八歲者,亦請勿將內容提供給未成年人士。