android: dynamically change FAB(Floating Action Button) icon from code
Solution 1
Changing FloatingActionButton source:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
floatingActionButton.setImageDrawable(getResources().getDrawable(R.drawable.ic_full_sad, context.getTheme()));
} else {
floatingActionButton.setImageDrawable(getResources().getDrawable(R.drawable.ic_full_sad));
}
This can be replaced by following code from the support library instead:
floatingActionButton.setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.ic_full_sad));
Solution 2
If you are using the Support Library:
floatingActionButton.setImageResource(R.drawable.icon_name)
Solution 3
Or you use the Support Library:
floatingActionButton.setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.ic_full_sad));
Solution 4
Assume that you will use the image ic_arrow_forward.png
as your fab's background:
fab.setImageResource(R.mipmap.ic_arrow_forward);
Hirdesh Vishwdewa
Creative and Dependable JavaScript, Angular, PHP with 8 years of experience in building rich and interactive web/mobile applications. I try to be futuristic while writing code try to follow all the best coding practices of good maintainable code. I don't cry when my code breaks. I am open to learn and work on new technologies. I worked on following technologies yet- Angular, JavaScript, TypeScript, RxJS (NgRx), D3Js PHP (Laravel 5.7, Yii 1/2), MySQL AWS deployment integration using PHP SDK (CodeDeploy, CloudFormation, CodePipeline, EC2, S3) AngularJS, Angular2, jQuery REST API, HTML5, CSS, Joomla (2.5, 3.x) XMPP (Openfire/stropheJS)
Updated on July 22, 2022Comments
-
Hirdesh Vishwdewa almost 2 years
How to change FAB icon in an Activity during runtime. I have this code ->
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fabMainActivity);
I know this is possible using
fab.setBackgroundDrawable();
but i am a newbie to android, don't understand how to do this.Any help will be highly appreciated.
Thanks