// MovingBallView.java by Kari Laitinen // http://www.naturalprogramming.com/ // 2012-02-10 Own file for the MovingBallView class // 2021-01-14 Kotlin version generated in Android Studio. package moving.ball import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.util.AttributeSet import android.view.View class MovingBallView : View { var ball_center_point_x = 100 var ball_center_point_y = 100 var ball_color = Color.RED constructor(context: Context?) : super(context) { } // The following constructor is needed when MovingBallView object is // specified in an XML file, and is thus created automatically. constructor( context: Context?, attributes: AttributeSet? ) : super( context, attributes ) { setBackgroundColor( 0xFFF5F5F5.toInt() ) // white smoke color } public override fun onSizeChanged( current_width_of_this_view: Int, current_height_of_this_view: Int, old_width_of_this_view: Int, old_height_of_this_view: Int) { ball_center_point_x = current_width_of_this_view / 2 ball_center_point_y = current_height_of_this_view / 2 } fun move_ball_left() { ball_center_point_x -= 3 invalidate() } fun move_ball_down() { ball_center_point_y += 3 invalidate() } fun move_ball_up() { ball_center_point_y -= 3 invalidate() } fun move_ball_right() { ball_center_point_x += 3 invalidate() } fun set_ball_color( new_color: Int ) { ball_color = new_color invalidate() } override fun onDraw( canvas: Canvas ) { val filling_paint = Paint() filling_paint.style = Paint.Style.FILL filling_paint.color = ball_color canvas.drawCircle(ball_center_point_x.toFloat(), ball_center_point_y.toFloat(), 64f, filling_paint) val outline_paint = Paint() outline_paint.style = Paint.Style.STROKE // Default color for a Paint is black. canvas.drawCircle( ball_center_point_x.toFloat(), ball_center_point_y.toFloat(), 64f, outline_paint ) canvas.drawText( "(" + ball_center_point_x + ", " + ball_center_point_y + ")", 20f, 20f, outline_paint ) } }