Vector path fill color not changing as dark/light theme color android

To change the fill color of a vector path in an Android app depending on the dark or light theme, you can use the ContextCompat.getColor method to dynamically retrieve the appropriate color from the current theme. Here's an example:


kotlin

Copy code

private fun setPathFillColor(path: Path, context: Context) {

    val color = ContextCompat.getColor(context, if (isDarkTheme(context)) R.color.dark_color else R.color.light_color)

    path.fillColor = color

}


private fun isDarkTheme(context: Context): Boolean {

    return context.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES

}

In this example, the setPathFillColor method sets the fill color of the Path object based on the current theme. The isDarkTheme method returns true if the current theme is dark and false if it's light. The fill color is determined by calling ContextCompat.getColor with the appropriate color resource ID.


Note that in this example, you would need to define the dark_color and light_color color resources in your app's colors.xml file.


In your layout XML file, you can use the setPathFillColor method in the onDraw method of a custom view that draws the vector path. Here's an example:


kotlin

Copy code

class VectorPathView @JvmOverloads constructor(

    context: Context,

    attrs: AttributeSet? = null,

    defStyleAttr: Int = 0

) : View(context, attrs, defStyleAttr) {


    private val path = Path()


    override fun onDraw(canvas: Canvas) {

        super.onDraw(canvas)

        setPathFillColor(path, context)

        canvas.drawPath(path, Paint().apply { isAntiAlias = true })

    }

}

In this example, the VectorPathView is a custom view that draws the vector path. The setPathFillColor method is called in the onDraw method to set the fill color of the path based on the current theme. The Paint object is used to draw the path on the canvas.


By dynamically setting the fill color of the vector path based on the current theme, you can ensure that the color is always appropriate for the current environment, whether the user has selected a dark or light theme.

Post a Comment

Previous Post Next Post