简体   繁体   中英

Which is better way to declare color between in resource file and assign a color to val directly when I use Jetpack Compose?

When I create a new Jetpack Compose project using the Android Studio wizard, I find color in both the resource XML file and Kotlin file.

I need to use colors for both Compose fun and Non compose fun, which is the better way between Code A and Code B?

Code A

val Purple200 = Color(0xFFBB86FC)
val Purple500 = Color(0xFF6200EE)

Code B

<resources>
    <color name="purple_200">#FFBB86FC</color>
    <color name="purple_500">#FF6200EE</color>   
</resources>

If the project has both Jetpack compose code and view-based code. Use the colors directly from the XML resource file.

colorResource

colorResource(R.color.purple_200)

The above code can access the XML color resources from Compose functions.


This way is okay if you are migrating a View-based project to Jetpack Compose.

But, if you are starting a new complete Compose project or after complete migration of a view-based project to Jetpack compose, it is recommended to use the colors from the Colors.kt file.


Note: This answer is not opinion based.
Jetpack compose can access colors from XML resources properly.
But the other way (accessing color using code in a View-based system) is not possible.

We have to consider the component theme, feature theme, dark or light mode, etc as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM