Change FAB color via code ( programmatically )

Asked

Viewed 202 times

1

I’m developing a Activity customized, where the colors of the screen elements will vary according to their properties.

Example: If the property guy of the object Message exhibited is "Azul", then the following file elements colors.xml will be used:

    <item name="azulFundo" type="color">#979dfd</item>
    <item name="azulTexto" type="color">#0011ff</item>
    <item name="azulFundoFab" type="color">#343b93</item>

For this, I do the following in the method onCreate:

          @Override
         protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.activity_mensagem_view); 

           mView = RelativeLayout.class.cast(findViewById(R.id.activity_mensagem_view)); 
           compartilharAction = FloatingActionButton.class.cast(findViewById(R.id.compartilharAction));
           imagemTipo = ImageView.class.cast(findViewById(R.id.imagemTipo));
           textMensagem = TextView.class.cast(findViewById(R.id.textMensagem ));
           final String tipo = getIntent().getStringExtra(MESSAGE_TYPE);

          if("Azul".equals(tipo)){ 
              mView.setBackgroundColor(ContextCompat.getColor(getBaseContext(), R.color.azulFundo)); 
              imageType.setImageDrawable(ContextCompat.getDrawable(getBaseContext(), R.drawable.azulImagem));  
              textMessage.setTextColor(ContextCompat.getColor( getBaseContext(), R.color.colorAguaTxt) ); 
              compartilharAction.setBackgroundResource(R.color.azulTexto);

          }else...


      }

I tried through the setBackgroundResource, but it didn’t work!

Any hint?

1 answer

3


Of documentation:

The background color of this view defaults to the your Theme’s colorAccent. If you Wish to change this at Runtime then you can do so via setBackgroundTintList(Colorstatelist).

Direct translation:

The background color of this pattern of this view is the colorAccent of your theme. If you want to change this at runtime, then you can do it through setBackgroundTintList (ColorStateList).

Then see how it can be done:

compartilharAction.setBackgroundTintList(ColorStateList.valueOf(
    ContextCompat.getColor(getBaseContext(), R.color.azulFundo)));

Browser other questions tagged

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