Know the color of Button Android Studio (Java)

Asked

Viewed 206 times

1

Good afternoon, I need to know how to read the color of the Button and store in a variable in java for Android platform but is showing errors, can help me ? Follow my code below:

private EditText cor;
public Button coreshexa;


coreshexa = (Button) findViewById( R.id.btn1);
cor = (EditText) findViewById( R.id.txtviewcorcateg);
ColorDrawable buttonColor = (ColorDrawable) coreshexa.getBackground();
cor.setText((CharSequence) buttonColor);
  • Which error is giving? and pass more code information, you are initiating variables in which method?

  • When I click the button to read the background of the button it says that the application has stopped, only this command is showing error in the application, the idea is to make a color palette with buttons and read the hexadecimal of the chosen button

  • Ola Matheus, you managed to solve by my answer?

1 answer

1


by your example do the following:

ColorDrawable buttonColor = (ColorDrawable) coreshexa.getBackground();

//recupera a cor do botão como inteiro
int colorInt = buttonColor.getColor();

//transforma o inteiro da cor em hexadecimal
String colorHex = Integer.toHexString(colorInt);

cor.setText(colorHex);

If you want to use the button color on another button:

//se for usar em Hex:
coreshexa.setBackgroundColor(Color.parseColor("#"+colorHex));
//se for usar em int:
coreshexa.setBackgroundColor(colorInt);
  • Thank you very much Murilo, sorry for the delay to give a return but your code my helped a lot, thanks for the help.

  • 1

    @Matheusribeiro, If the answer helped you, please mark it as answered and/or as useful.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.