How to programmatically set backgroundTint of FloatingActionButton with ColorStateList?
Solution 1
This issue has been resolved as of Android Support Library 25.1.0
See: https://code.google.com/p/android/issues/detail?id=227428
Solution 2
use this:
fab.setBackgroundTintList(ContextCompat.getColorStateList(getApplicationContext(), R.color.purple_200));
Solution 3
Since setBackgroundTintList
is only supported in API 21+ you can use ViewCompat.
ViewCompat.setBackgroundTintList(
fab,
ContextCompat.getColorStateList(
getApplicationContext(),
R.color.purple_200
)
);
Related videos on Youtube
Comments
-
Zach almost 2 years
Programmatically setting my
FloatingActionButton
'sbackgroundTint
viasetBackgroundTintList
method does not work, but setting it via XMLapp: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?
-
Zach over 7 yearsI'm not seeing any difference in behavior unfortunately. Thanks though.
-
Nathan F. over 4 yearsrequires api 21+