Analyze Android Multi-Theme color issues _android

Source: Internet
Author: User
Tags getcolor

If you use the following code to get the defined color value

Context.getresources (). GetColor (r.color.some_color_resource_id);

There is a lint warning in Android Studio that prompts you to Resources#getColor(int) Marshmallow be discarded in, and suggests using a topic-knowable Resources#getColor(int, Theme function. To avoid this warning, you can use ContextCompat :

Contextcompat.getcolor (context, r.color.some_color_resource_id);

The implementation of this function is like this:

if (Build.VERSION.SDK_INT >= build.version_codes. M) {return
 context.getresources (). GetColor (ID, context.gettheme ());
 Context.getresources (). GetColor (ID);
}

It looks very simple. But why is that? Why would you start using a theme-themed function to discard previous functions?

Problems with Resources#getcolor (int) & Resources#getcolorstatelist (int)

Let's take a look at what these two obsolete functions do:
Resources#getColor(int) returns the color value that corresponds to a resource ID, if the resource is the ColorStateList ColorStateList default color value returned

Resources#getColorStateList(int) returns the correspondingColorStateList

Under what circumstances will the above code break my code?

To understand why these two functions are discarded, look at a colorstatelist example. When a custom colorstatelist is used in TextView, the TextView cannot be used and represented separately from the text color of the state and the available state R.attr.colorAccent R.attr.colorPrimary .

Xhtml

<selector xmlns:android= "Http://schemas.android.com/apk/res/android" >
  <item android:color= "? attr/ Coloraccent "android:state_enabled=" false "/>
  <item android:color=" attr/colorprimary "/> </
Selector>

Now if you get this by using the following codeColorStateList

Colorstatelist CSL = Context.getresources (). Getcolorstatelist (R.COLOR.BUTTON_TEXT_CSL);

The above code throws an exception (see Logcat can see the following information)

W/resources:colorstatelist COLOR/BUTTON_TEXT_CSL has unresolved theme
       attributes! Consider using resources.getcolorstatelist (int, Theme)
       or context.getcolorstatelist (int)
    at Android.content.res.Resources.getColorStateList (resources.java:1011) ...
    

Where did it go wrong?

The root of the problem is that the Resources object is not associated with an Theme object, and when using R.attr.colorAccent and R.attr.colorPrimary referring to the color, the result cannot be resolved by not specifying the corresponding theme in the code when it is parsed through the function above. So the Marshmallow support for Theme is added and the ColorStateList two new functions are added: Resources#getColor(int, Theme) and Resources#getColorStateList(int, Theme), The Theme parameters are used to parse the attributes attributes inside.

The corresponding implementations are also available in the new version of the Support library, respectively, in the ResourcesCompat and ContextCompat class.

How do you solve the problem?

Using the AppCompat v24+ version makes it easy to solve the problem.

Colorstatelist CSL = appcompatresources.getcolorstatelist (context, R.COLOR.BUTTON_TEXT_CSL);

Using the system's functions directly on the 23+ version, the previous version AppCompat itself to parse these XML files from the inside to extract the value of the attr attribute. AppCompat also supports colorstatelist of new android:alpha properties.

Problems with resources#getdrawable (int)

Resources#getDrawable(int) The problem with the previous two functions is similar. Theme attr is not supported in versions prior to Lollipop.

Why is it that I'm not doing anything unusual?

Exceptions are not always present.

VectorDrawableCompatand classes AnimatedVectorDrawableCompat are added to the AppCompatResources same functionality as the class. For example, in a vector diagram you can use ?attr/colorControlNormal to set the color of the vector graph, VectorDrawableCompat will automatically complete the work to resolve this property:

Xhtml

<vector 
  xmlns:android= "http://schemas.android.com/apk/res/android"
  android:width= "24DP
  " android:height= "24DP"
  android:viewportwidth= "24.0"
  android:viewportheight= "24.0" android:tint= "
  ? attr/colorcontrolnormal ">
 
  <path
    android:pathdata=" ... "
    android:fillcolor=" @android: Color /white "/>
</vector>

Small test

Here's a little test to review what you've described earlier. Suppose you have one of the following colorstatelist:

Xhtml

<!--res/colors/button_text_csl.xml-->
<selector xmlns:android= "http://schemas.android.com/apk/res/ Android ">
  <item android:color=" "Attr/coloraccent" android:state_enabled= "false"/>
  <item Android:color= "Attr/colorprimary"/>
</selector>

The following Theme are defined in the application:

Xhtml

<!--res/values/themes.xml-->
<style name= "Apptheme" parent= "Theme.AppCompat.Light.DarkActionBar" >
  <item name= "colorprimary" > @color/vanillared500</item>
  <item name= "Colorprimarydark" > @color/vanillared700</item>
  <item name= "coloraccent" > @color/googgreen500</item>
</style>
 
<style name= "Custombuttontheme" parent= "ThemeOverlay.AppCompat.Light" >
  <item Name = "Colorprimary" > @color/brown500</item>
  <item name= "coloraccent" > @color/yellow900</item >
</style>

The following functions are used in your code to resolve color values and create Colorstatelist in your code:

@ColorInt
private static int Getthemeattrcolor (context context, @AttrRes int colorattr) {
 TypedArray array = cont Ext.obtainstyledattributes (NULL, New int[]{colorattr});
 try {return
  array.getcolor (0, 0);
 } finally {
  array.recycle ();
 
}} private static Colorstatelist Createcolorstatelist {return
 new Colorstatelist (
   new int[][) {
     new int[]{-android. R.attr.state_enabled},//Disabled state.
     Stateset.wild_card,            //Enabled state.
   }, the
   new int[]{
     getthemeattrcolor (context, r.attr.coloraccent),//Disabled state.
     Getthemeattrcolor (context, r.attr.colorprimary),//Enabled state.
   }

See if you can guess the color of the text disabled and normal in API 19 and API 23, as shown in the following code (5 and 8, specified in TextView XML android:theme=”@style/CustomButtonTheme” ):

Resources res = ctx.getresources ();
(1) int deprecatedtextcolor = Res.getcolor (R.COLOR.BUTTON_TEXT_CSL);
 
Button1.settextcolor (Deprecatedtextcolor);
(2) Colorstatelist DEPRECATEDTEXTCSL = Res.getcolorstatelist (R.COLOR.BUTTON_TEXT_CSL);
 
Button2.settextcolor (DEPRECATEDTEXTCSL);
(3) int textcolorxml = Appcompatresources.getcolorstatelist (CTX, R.COLOR.BUTTON_TEXT_CSL). Getdefaultcolor ();
 
Button3.settextcolor (Textcolorxml);
(4) Colorstatelist textcslxml = Appcompatresources.getcolorstatelist (CTX, R.COLOR.BUTTON_TEXT_CSL);
 
Button4.settextcolor (Textcslxml);
(5) Context themedctx = Button5.getcontext (); Colorstatelist textcslxmlwithcustomtheme = appcompatresources.getcolorstatelist (ThemedCtx, R.COLOR.BUTTON_TEXT_CSL
);
 
Button5.settextcolor (Textcslxmlwithcustomtheme);
(6) int textcolorjava = Getthemeattrcolor (CTX, r.attr.colorprimary);
 
Button6.settextcolor (Textcolorjava);
(7) Colorstatelist Textcsljava = Createcolorstatelist (CTX); Button7.settextcolor (TEXTCSljava);
(8) Context Themedctx = Button8.getcontext ();
Colorstatelist textcsljavawithcustomtheme = createcolorstatelist (THEMEDCTX); Button8.settextcolor (Textcsljavawithcustomtheme);

Here is a screenshot of the corresponding implementation:

Summarize

These are all the things about analyzing Android's multiple theme colors, and hopefully this article will help you develop Android.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.