Search code examples
androidbuttoncolorsdrawablebackground-color

How to get Background Shape color of buttons?


I have 9 custom round buttons each when clicked opens the color picker and a save button at bottom view retrieves all the data .

My problem is i am not able to retrieve the color correctly.and also the code can retrieve the data above 24 version .that is also useless. Debugger output Sample code

This code is invoked everytime the button is click .it gets the color value from color picker.

GradientDrawable c1, c2;
  Button mcbt_1,mcbt_2;

           // this function gets call everytime button is clicked ,it sets the color to the background and maintain the shape of button to circle.
            public void onColorSelected(int color) {
                switch (buttonSelected) {
                    case 1:
                        c1 = (GradientDrawable) Mcbt_1.getBackground();
                        c1.setColor(color);
                        break;
                    case 2:
                        c2 = (GradientDrawable) Mcbt_2.getBackground();
                        c2.setColor(color);
                        break;

                }
            }

This code gets the background color of the buttons present in the view.But major issue is version support. and also data i am getting is last color value of button. for example: if int color1 = (-15210) for button 1 and int color2 =(-15700) then when i get the value using this

   c1 = (GradientDrawable) Mcbt_1.getBackground();
                            color_BT_1 = c1.getColor().getDefaultColor();

from the above code i get color_BT_1 as -15700 and color_BT_2 as -15700.

 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                        c1 = (GradientDrawable) Mcbt_1.getBackground();
                        color_BT_1 = c1.getColor().getDefaultColor();

                        c2 = (GradientDrawable) Mcbt_2.getBackground();
                        color_BT_2 = c2.getColor().getDefaultColor();

                       String edColor = color_BT_1 + "," + color_BT_2 ;
}

Solution

  • To getColor of Background Below API 24, you have to use ColorDrawable. The documentation for the same can be found over here docmentation and in this answer as well.

    The problem was in saving the values of the color rather than getting it.

    I hope this helps.