2011年2月8日火曜日

onTouchEventを利用して日の丸を動かす - Moving a rising sun flag using onTouchEvent method -

このエントリーをはてなブックマークに追加
アンドロイド携帯の画面をタッチ、ドラッグしたときの動作はonTouchEventメソッドを利用することで実現できます。ここでは、日の丸をタッチしたときに色を変え、ドラッグしたときに日の丸を動かすコードを記述ています。

The operation when the screen of the android mobile phone is touched and dragged can be coded using onTouchEvent method. We described the code in which the rising sun flag is changed on its color and is moved when it is touched and is dragged.



Canvasクラスを利用して日の丸を描くの続きです。

onTouchEventとMotionEvent
タッチイベントはActivityクラスのonTouchEventをオーバーライドすることで実現できます。タッチイベントが検出されると、そのイベント情報を持ったMotionEventのインスタンスが引数として渡されます。アクションの種類は、MotionEventのgetActionメソッドによって取得でき、次のようなアクションが含まれています。

MotionEvent.ACITON_DOWN
指が画面に触れたとき(タッチ)

MotionEvent.ACITON_MOVE
タッチした状態で指を動かしたとき(ドラッグ)

MotionEvent.ACITON_UP
指が画面から離れたとき


ソースコード
ソースコードは次のアクションを実現するように記述しました。
・タッチしたとき赤丸を青丸にする
・ドラッグすると青丸が動く
・画面から指を離すと青丸が赤丸にする

/LayoutTest/src/org/example/layout/BetaView.java
package org.example.layout;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.View;

public class BetaView extends View{

     private int circleColor = 0xffff0000;
     private int circleWidth = 0;
     private int circleHeight = 0;

     public BetaView(Context context) {
          super(context);
     }

     @Override
     protected void onDraw(Canvas canvas) {
          Paint rect = new Paint();
          rect.setColor(0xffffffff);
          canvas.drawRect(0, 0, getWidth(), getHeight(), rect);

          Paint circle = new Paint();
          circle.setColor(circleColor);
          canvas.drawCircle(circleWidth, circleHeight, 90, circle);
     }

     @Override
     protected void onSizeChanged(int w, int h, int oldw, int oldh) {
          circleWidth = w / 2;
          circleHeight = h / 2;
     }

     @Override
     public boolean onTouchEvent(MotionEvent event) {

          switch(event.getAction()) {
          case MotionEvent.ACTION_DOWN:
               circleColor = 0xff0000ff;
               break;
          case MotionEvent.ACTION_MOVE:
               circleWidth = (int) event.getX();
               circleHeight = (int) event.getY();
               break;
          case MotionEvent.ACTION_UP:
               circleColor = 0xffff0000;
               break;
          }
          invalidate();

          return true;
     }
}

invalidateは画面を再描画するメソッドで、間接的にonDrawを呼び出します。onSizeChangedメソッドは画面サイズがわかった時点で呼び出されるメソッドであり。初期起動時や画面を縦から横にした時などに呼ばれます。


実行結果
エミュレータでの確認です。

初期状態


クリック(タッチ)すると青丸に変更


ドラッグすると丸が移動


クリック状態をやめる(指を離す)と赤丸に変更


動かせるって素晴らしい!

0 件のコメント:

コメントを投稿