Reputation: 774
I have two drawable pictures, initially FAB is set to R.drawable.icon1, I want to set it to R.drawable.icon2 when clicking on it, and setting it back to icon1 when clicking one more time on it and so on...
Is there a way to do that?
Any help is appreciated!
Upvotes: 4
Views: 6664
Reputation: 2893
I have created the following extension function for Kotlin to make the operation easier.
fun FloatingActionButton.icon(@DrawableRes id: Int = 0) {
setImageResource(id)
}
fun FloatingActionButton.backgroundColor(@ColorRes colorRes: Int = 0) {
backgroundTintList = ColorStateList.valueOf(ContextCompat.getColor(context, colorRes))
}
fun FloatingActionButton.iconColor(@ColorRes colorRes: Int = 0) {
imageTintList = ColorStateList.valueOf(ContextCompat.getColor(context, colorRes))
}
Sample:
var flag = true
binding.fabToggleService.setOnClickListener {
flag = !flag
if (flag) {
binding.fabToggleService.apply {
icon(R.drawable.ic_round_stop_24)
iconColor(R.color.white)
backgroundColor(R.color.md_red_400)
} else {
binding.fabToggleService.apply {
icon(R.drawable.ic_round_play_arrow_24)
iconColor(R.color.white)
backgroundColor(R.color.md_blue_400)
}
}
You can see the action live, see comment with link of one of my apps
Upvotes: 0
Reputation: 478
Hope this helps, we have a boolean flag
which denotes the current icon visible in your fab.
FloatingActionButton fab;
boolean flag = true; // true if first icon is visible, false if second one is visible.
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(flag){
fab.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.icon2));
flag = false;
}else if(!flag){
fab.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.icon1));
flag = true;
}
}
});
Upvotes: 11