Search code examples
javaandroidruntime-errornosuchmethoderror

Run-Time Error Regarding Set Button Tint List


Attempting to set the colour(s) of a radio button. I get no errors in the code and am able to run the app on various devices with no issues (API => 22), however, on certain devices (API 16) the app crashes and I am left with the following debug error:

java.lang.NoSuchMethodError: android.widget.CompoundButton.setButtonTintList

I can't see any obvious issues with the section of code (attached below) that would be effected by API 16. Any help would be much appreciated.

            CompoundButton t;

            t = new CheckBox(context);

            int[][] states = new int[][] {
                    new int[] { android.R.attr.state_enabled}, // enabled
                    new int[] {-android.R.attr.state_enabled}, // disabled
                    new int[] {-android.R.attr.state_checked}, // unchecked
                    new int[] { android.R.attr.state_pressed}  // pressed
            };

            int[] colors = new int[] {
                    Color.BLACK,
                    Color.RED,
                    Color.GREEN,
                    Color.BLUE
            };

            ColorStateList c = new ColorStateList(states, colors);
            t.setButtonTintList(c);

Solution

  • You can't use the native method setButtonTintList(ColorStateList) for API levels inferior than 21. You should use this compatibility method setButtonTintList(CompoundButton, ColorStateList) for older APIs. Read the documentation to understand how to use Support Libraries.