Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically set backgroundTint of FloatingActionButton with ColorStateList?

Programmatically setting my FloatingActionButton's backgroundTint via setBackgroundTintList method does not work, but setting it via XML app:backgroundTint tag does work - why is that?

The fab_background_color.xml color list state is:

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_selected="true"
          android:color="#654321"/>

    <item android:color="#123456"/>

</selector>

My activity layout is:

<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/test"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"/>

</android.support.design.widget.CoordinatorLayout>

and activity code:

public class SampleActivity extends AppCompatActivity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_position_sample);

        final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.test);

        // Uncomment to test - this does NOT work however.
        //fab.setBackgroundTintList(getResources().getColorStateList(R.color.fab_background_color));

        fab.setOnClickListener(new View.OnClickListener()
        {
            @Override public void onClick(View v)
            {
                if (fab.isSelected())
                    fab.setSelected(false);
                else
                    fab.setSelected(true);
            }
        });
    }
}

If I add:

fab.setBackgroundTintList(getResources().getColorStateList(R.color.fab_background_color));

or:

fab.setBackgroundTintList(ContextCompat.getColorStateList(this, R.color.fab_background_color));

To the activity code before setting up the click listener, nothing happens.

If I add:

app:backgroundTint="@color/fab_background_color"

To the activity layout code for the FloatingActionButton, I get the expected behavior.

Any thoughts? Am I doing something wrong?

like image 284
Zach Avatar asked Nov 04 '16 15:11

Zach


2 Answers

use this:

fab.setBackgroundTintList(ContextCompat.getColorStateList(getApplicationContext(), R.color.purple_200));

Cheers!

like image 118
noe Avatar answered Sep 28 '22 04:09

noe


Since setBackgroundTintList is only supported in API 21+ you can use ViewCompat.

ViewCompat.setBackgroundTintList(
    fab, 
    ContextCompat.getColorStateList(
        getApplicationContext(),
        R.color.purple_200
    )
);
like image 42
Nathan F. Avatar answered Sep 28 '22 04:09

Nathan F.