Android Touch 簡易觸控

在 Android 中可以藉由 onTouchEvent 事件,

來實現 Touch 觸控功能,

程式範例如下 :
 程式碼
public class helloWorld extends Activity {

private float touchX;
private float touchY;
private int tvWidth = LayoutParams.WRAP_CONTENT;
private int tvHeight = LayoutParams.WRAP_CONTENT;
private TextView tv = null;

/** Called when the activity is first created. */
@Override

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

// 取得 TextView 物件
tv = (TextView)findViewById(R.id.textWidget);
tv.setTextColor(0xffffff00);
}

@Override
// 利用 MotionEvent 處理觸控程序

public boolean onTouchEvent(MotionEvent event) {

touchX = event.getX(); // 觸控的 X 軸位置
touchY = event.getY() - 50; // 觸控的 Y 軸位置

// 判斷觸控動作
switch( event.getAction() ) {

case MotionEvent.ACTION_DOWN: // 按下

// 設定 TextView 內容, 大小, 位置
tv.setText("X: " + touchX + ", Y: " + touchY + ", 按下");
tv.setLayoutParams( new AbsoluteLayout.LayoutParams( tvWidth
, tvHeight
, (int)touchX
, (int)touchY
));
break;

case MotionEvent.ACTION_MOVE: // 拖曳移動

// 設定 TextView 內容, 大小, 位置
tv.setText("X: " + touchX + ", Y: " + touchY + ", 拖曳移動");
tv.setLayoutParams( new AbsoluteLayout.LayoutParams( tvWidth
, tvHeight
, (int)touchX
, (int)touchY
));
break;

case MotionEvent.ACTION_UP: // 放開

// 設定 TextView 內容
tv.setText("X: " + touchX + ", Y: " + touchY + ", 放開");
break;
}

// TODO Auto-generated method stub
return super.onTouchEvent(event);
}
}

範例結果 :




Related Posts Plugin for WordPress, Blogger...