简体   繁体   中英

Most efficient way to set TextView colour

What's the most efficient way to set the color of a TextView and why? Is there 1 method that is more memory and/or processor efficient? Or is there no difference at all to what happens with my app when it's running? Is it better to refer to a colour resource than declare RGB everytime I set a colour?

Option 1 (using RGB channel)

myTextView.setTextColor(Color.rgb(154,160,166))

Option 2 (using colour parser)

myTextView.setTextColor(Color.parseColor("#2B3A11"))

Option 3 (using colour resource from colors.xml )

myTextView.setTextColor(ContextCompat.getColor(context, R.color.<name_of_colour>))

Option 1 Should be the fastest way to set color to your TextView. With option 2 being a very closed Second. Because both RGB values and Hexcodes function in a similar way. It all comes down to the functions they are called from and how these functions are executed in the background (look rgb parseColor for these function's description and implementation ).

As myTextView.setTextColor(...) is the same. So what happens to your textview in the background remains the same only the picking up of color is done differently.

Is it better to refer to a color resource than declare RGB everytime I set a color?
Ans- It depends on the your own usage,for example

if you want to use a color multiple times and find it harder to remember the rgb code then you should definitely save the color int the color resource and refer to it later. The color resource was created for this purpose only right. And as @Fancesc mentioned it does make your documents readable and maintainable, Hence. the more professional way of doing things.


On the other hand using rgb right whenever needed saves you a lot of trouble.

  1. You don't need to save any data anywhere.
  2. While using you don't need to search the whole color resource file.
  3. 99% times the color model used is rgb/rgba, so everything you do ends up here.
  4. Plus newer updates make it easier to work on rgb and hex values for colors. one such example is shown here .
  5. Good for people who are bad with color names.



I am assuming you knew all of this already but decided to ask it anyways.XD. Have a good Day.

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