Exercise : 20
Create an application
to draw line on the screen as user drag his finger.
Screen Shot:
XML :
main.xml :
main.xml :
JAVA :
TwentyActivity.java :
package kmn.Twenty;
import android.app.Activity;
import android.os.Bundle;
public class TwentyActivity extends Activity
{
/** @author Y@@D */
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
setContentView(new ExploreTouchEvent(this, null));
}
}
ExploreTouchEvent.java :
package kmn.Twenty;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
/** @author Y@@D */
public class ExploreTouchEvent extends View
{
private Paint paint = new Paint();
private Path path = new Path();
public ExploreTouchEvent(Context context, AttributeSet attrs)
{
super(context, attrs);
paint.setAntiAlias(true);
paint.setStrokeWidth(6f);
paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
}
protected void onDraw(Canvas canvas)
{
canvas.drawColor(Color.BLUE);
canvas.drawPath(path, paint);
}
public boolean onTouchEvent(MotionEvent event)
{
float eventX = event.getX();
float eventY = event.getY();
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
path.moveTo(eventX, eventY);
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(eventX, eventY);
break;
case MotionEvent.ACTION_UP:
// nothing to do
break;
default:
return false;
}
// Schedules a repaint.
invalidate();
return true;
}
}
