Reputation: 71
I want to use the floating action button as some sort of a favorite button, i.e. a bookmark function. I am using a boolean
, initialized like so:
boolean favSelected = false;
and my activity will retrieve some information from my SQLite database to determine whether favSelected
will be true or false. If it's true, I would want my fab to be in a different color, and if false the original color. I tried this:
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(favSelected = false) {
favSelected = true;
fab.setBackgroundTintList(new ColorStateList(new int[][]{new int[]{0}}, new int[]{getResources().getColor(R.color.header_pressed)}));
} else if ( favSelected = true){
favSelected = false;
fab.setBackgroundTintList(new ColorStateList(new int[][]{new int[]{0}}, new int[]{getResources().getColor(R.color.colorPrimary)}));
}
}
});
but it didn't work. The intended function is a bit like a checkbox
Upvotes: 0
Views: 2353
Reputation: 4357
You are using if(favSelected = false)
This is assignment to favSelected, Please use as if(favSelected == false)
.
For comparisons we use ==
sign instead of =
so Modify your code like this
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void onClick(View view) {
if (!favSelected) {
favSelected = true;
view.setBackgroundTintList(new ColorStateList(new int[][]
{new int[]{0}}, new int[]{getResources().getColor(R.color.colorAccent)}));
} else if (favSelected) {
favSelected = false;
view.setBackgroundTintList(new ColorStateList(new int[][]{new int[]{0}}, new int[]{getResources().getColor(R.color.colorPrimary)}));
}
}
});
Upvotes: 1
Reputation: 15155
Try this code to change your FAB color on pressed state:
int[][] states = new int[][]{
new int[]{android.R.attr.state_pressed},
new int[]{-android.R.attr.state_pressed},
new int[]{android.R.attr.state_focused},
new int[]{-android.R.attr.state_pressed}
};
int[] colors = new int[]{
ContextCompat.getColor(this, R.color.color_pressed),
ContextCompat.getColor(this, R.color.color_normal),
ContextCompat.getColor(this, R.color.color_pressed),
ContextCompat.getColor(this, R.color.color_normal)
};
fab.setBackgroundTintList(new ColorStateList(states, colors));
Upvotes: 2