Skip to content

Instantly share code, notes, and snippets.

@ShivamKumarJha
Created May 17, 2025 01:21
Show Gist options
  • Save ShivamKumarJha/be10a41a7f112f10d640ea0bec35799f to your computer and use it in GitHub Desktop.
Save ShivamKumarJha/be10a41a7f112f10d640ea0bec35799f to your computer and use it in GitHub Desktop.
LinearProgressIndicator, similar to Material 2 LinearProgressIndicator
package com.example.rideblitzandroidapp.common.ui
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import com.example.rideblitzandroidapp.R
import com.example.rideblitzandroidapp.common.util.extension.dp
import com.example.rideblitzandroidapp.common.util.extension.getColorById
class LinearProgressIndicator @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null
) : View(context, attrs) {
private var progress: Int = 0
private var indicatorColor: Int = context.getColorById(R.color.primary_blue)
private var trackColor: Int = context.getColorById(R.color.primary_light)
private var trackCornerRadius: Int = 8.dp
private val trackPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.FILL
}
private val indicatorPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.FILL
}
fun setProgress(value: Int) {
progress = value.coerceIn(0, 100)
invalidate()
}
fun setIndicatorColor(color: Int) {
indicatorColor = color
invalidate()
}
fun setTrackColor(color: Int) {
trackColor = color
invalidate()
}
fun setTrackCornerRadius(radiusDp: Int) {
trackCornerRadius = radiusDp
invalidate()
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val width = width.toFloat()
val height = height.toFloat()
val progressWidth = width * (progress / 100f)
// Draw track
trackPaint.color = trackColor
canvas.drawRoundRect(
0f,
0f,
width,
height,
trackCornerRadius.toFloat(),
trackCornerRadius.toFloat(),
trackPaint
)
// Draw indicator
indicatorPaint.color = indicatorColor
canvas.drawRoundRect(
0f,
0f,
progressWidth,
height,
trackCornerRadius.toFloat(),
trackCornerRadius.toFloat(),
indicatorPaint
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment