Androidでドラッグイベント取得
Androidは基本的にタッチパネルも使える模様。しかも、使い方は一般的な マウスイベントの取り方とあんまり変わらないので超便利。
package net.chephes.androidtest;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import java.net.*;
import java.io.*;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.*;
public class AndroidTest extends Activity {
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(new MyView(this));
}
public class MyView extends View {
Bitmap mBitmap;
Canvas mCanvas;
private final Paint mPaint;
private boolean curDown;
private Drawable d;
private int offsetX, offsetY;
private int curX, curY;
private int imgX, imgY;
private int imgW, imgH;
public MyView(Context c) {
super(c);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setARGB(255, 255, 255, 255);
d = loadImage("http://www.google.com/images/google_sm.gif");
}
public Drawable loadImage(String str){
Drawable d = null;
try{
URL url = new URL(str);
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setRequestMethod("GET");
http.connect();
InputStream in = http.getInputStream();
d = Drawable.createFromStream(in, "a");
in.close();
}catch(Exception e){
}
imgX = 20;
imgY = 20;
imgW = 143;
imgH = 59;
d.setBounds(imgX, imgY, imgX + imgW, imgY + imgH);
return d;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
int curW = mBitmap != null ? mBitmap.width() : 0;
int curH = mBitmap != null ? mBitmap.height() : 0;
if (curW >= w && curH >= h) {
return;
}
if (curW < w) curW = w;
if (curH < h) curH = h;
Bitmap newBitmap = Bitmap.createBitmap(curW, curH, false);
Canvas newCanvas = new Canvas();
newCanvas.setDevice(newBitmap);
if (mBitmap != null) {
newCanvas.drawBitmap(mBitmap, 0, 0, null);
}
mBitmap = newBitmap;
mCanvas = newCanvas;
}
@Override
protected void onDraw(Canvas canvas) {
if (mBitmap != null) {
canvas.drawBitmap(mBitmap, 0, 0, null);
d.draw(canvas);
}
}
@Override
public boolean onMotionEvent(MotionEvent event) {
int action = event.getAction();
curX = (int)event.getX();
curY = (int)event.getY();
if(action == MotionEvent.ACTION_DOWN){
offsetX = curX - imgX;
offsetY = curY - imgY;
curDown = true;
}else if(action == MotionEvent.ACTION_UP){
curDown = false;
}else if(curDown && action == MotionEvent.ACTION_MOVE){
imgX = curX - offsetX;
imgY = curY - offsetY;
d.setBounds(imgX, imgY, imgX + imgW, imgY + imgH);
invalidate();
}
return true;
}
}
}
とりあえず動くのができたのでアップしてみる。
いろいろと試しまくっているので、いらないimport文とか結構ありそうなので、 なんか見つけたら教えてください。
11/14追記
上記のプログラムは若干挙動に問題があります。画像以外の箇所をドラッグしても、画像が移動してしまいます。近いうちに修正版をアップするので、お待ちください。
| 固定リンク
「Android」カテゴリの記事
- Androidでお電話(2008.02.22)
- AndroidSDK感想(2008.02.14)
- Androidがバージョンアップ!!(2008.02.14)
- まとめてみた-。(2008.01.31)
- Androidの非公式実機が登場!(2007.12.07)


コメント