Drag and move a dot : Drag Drop « UI « Android






Drag and move a dot

   

package app.test;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

class Dot extends View {
  private static final float RADIUS = 20;
  private float x = 30;
  private float y = 30;
  private float initialX;
  private float initialY;
  private float offsetX;
  private float offsetY;
  private Paint myPaint;
  private Paint backgroundPaint;

  public Dot(Context context, AttributeSet attrs) {
    super(context, attrs);

    backgroundPaint = new Paint();
    backgroundPaint.setColor(Color.BLUE);

    myPaint = new Paint();
    myPaint.setColor(Color.WHITE);
    myPaint.setAntiAlias(true);
  }

  public boolean onTouchEvent(MotionEvent event) {
    int action = event.getAction();
    switch (action) {
    case MotionEvent.ACTION_DOWN:
      initialX = x;
      initialY = y;
      offsetX = event.getX();
      offsetY = event.getY();
      break;
    case MotionEvent.ACTION_MOVE:
    case MotionEvent.ACTION_UP:
    case MotionEvent.ACTION_CANCEL:
      x = initialX + event.getX() - offsetX;
      y = initialY + event.getY() - offsetY;
      break;
    }
    return (true);
  }

  public void draw(Canvas canvas) {
    int width = canvas.getWidth();
    int height = canvas.getHeight();
    canvas.drawRect(0, 0, width, height, backgroundPaint);
    canvas.drawCircle(x, y, RADIUS, myPaint);
    invalidate();
  }
}

public class Test extends Activity {
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
  }
}

//main.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- This file is res/layout/main.xml -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"  android:layout_height="fill_parent" >

  <app.test.Dot
    android:id="@+id/dot"  android:tag="trueDot"
    android:layout_width="wrap_content"  android:layout_height="wrap_content" />
</LinearLayout>

   
    
    
  








Related examples in the same category

1.Draggable dot
2.Drag and drop