create the simple progress bar in android studio using the canvas in kotlin
To create a custom progress bar using Canvas
in Android, you can override the onDraw()
method of a View
and use Paint
to draw the progress on the Canvas
. Here’s how you can do it:
Step 1: Create a Custom View Class
class CustomProgressBar(context: Context, attrs: AttributeSet) : View(context, attrs) {
private var progress = 0f
private val maxProgress = 100f
private val progressBarPaint: Paint = Paint()
private val backgroundPaint: Paint = Paint()
init {
// Set up paint for progress bar
// set the color of progress bar
progressBarPaint.color = Color.BLUE
progressBarPaint.strokeWidth = 10f
progressBarPaint.isAntiAlias = true
progressBarPaint.style = Paint.Style.FILL
// Set up paint for background
backgroundPaint.color = Color.LTGRAY
backgroundPaint.strokeWidth = 10f
backgroundPaint.isAntiAlias = true
backgroundPaint.style = Paint.Style.FILL
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
// Draw the background of the progress bar
val width = width.toFloat()
val height = height.toFloat()
canvas.drawRect(0f, 0f, width, height, backgroundPaint)
// Draw the progress bar
val progressWidth = (progress / maxProgress) * width
canvas.drawRect(0f, 0f, progressWidth, height, progressBarPaint)
}
// Method to update the progress
fun setProgress(progress: Float) {
this.progress = progress
invalidate() // Request a redraw
}
// Method to get current progress
fun getProgress(): Float {
return progress
}
}
Step 2: Add the Custom View to Layout
Now, you can add this CustomProgressBar
to your XML layout:
// my package name is with complete line <com.lit2talks.canvas.CustomProgressBar
<com.yourpackage.CustomProgressBar
android:id="@+id/customProgressBar"
android:layout_width="match_parent"
android:layout_height="20dp"
android:layout_marginTop="20dp" />
Step 3: Control Progress in Your Activity/Fragment
To update the progress, you can call the setProgress()
method from your activity or fragment:
val customProgressBar = findViewById<CustomProgressBar>(R.id.customProgressBar)
// Set progress to 50%
customProgressBar.setProgress(50f)
Optional: Animating the Progress
If you want to animate the progress bar, you can use ValueAnimator
to smoothly update the progress value:
val animator = ValueAnimator.ofFloat(0f, 100f) // Animation from 0 to 100%
animator.duration = 1000 // 1 second duration
animator.addUpdateListener {
val value = it.animatedValue as Float
customProgressBar.setProgress(value)
}
animator.start()