// MovingBallView.java by Kari Laitinen // http://www.naturalprogramming.com/ // 2012-02-10 Own file for the MovingBallView class // 2015-03-14 Last modification. package moving.ball ; import android.graphics.* ; import android.view.* ; import android.content.Context ; import android.util.AttributeSet ; public class MovingBallView extends View { int ball_center_point_x = 100 ; int ball_center_point_y = 100 ; int ball_color = Color.RED ; public MovingBallView( Context context ) { super( context ) ; } // The following constructor is needed when MovingBallView object is // specified in an XML file, and is thus created automatically. public MovingBallView( Context context, AttributeSet attributes ) { super( context, attributes ) ; setBackgroundColor( 0xFFFFFFE0 ) ; // Light Yellow } public void onSizeChanged( int current_width_of_this_view, int current_height_of_this_view, int old_width_of_this_view, int old_height_of_this_view ) { ball_center_point_x = current_width_of_this_view / 2 ; ball_center_point_y = current_height_of_this_view / 2 ; } public void move_ball_left() { ball_center_point_x -= 3 ; invalidate() ; } public void move_ball_down() { ball_center_point_y += 3 ; invalidate() ; } public void move_ball_up() { ball_center_point_y -= 3 ; invalidate() ; } public void move_ball_right() { ball_center_point_x += 3 ; invalidate() ; } public void set_ball_color( int new_color ) { ball_color = new_color ; invalidate() ; } @Override protected void onDraw( Canvas canvas ) { Paint filling_paint = new Paint() ; filling_paint.setStyle( Paint.Style.FILL ) ; filling_paint.setColor( ball_color ) ; canvas.drawCircle( ball_center_point_x, ball_center_point_y, 64, filling_paint ) ; Paint outline_paint = new Paint() ; outline_paint.setStyle( Paint.Style.STROKE ) ; // Default color for a Paint is black. canvas.drawCircle( ball_center_point_x, ball_center_point_y, 64, outline_paint ) ; canvas.drawText( "(" + ball_center_point_x + ", " + ball_center_point_y + ")", 20, 20, outline_paint ) ; } }