MacaronLover MacaronLover - 1 year ago 176
Java Question

"Field can be converted to a local variable" message appearing when setting action bar colour

After setting the colour of the action bar,

private String actionBarColor = "#B36305";
gets highlighted yellow and a warning is returned for some reason. What can be done to get rid of this warning?

Field can be converted to a local variable

public class MainActivity extends AppCompatActivity {

private String actionBarColor = "#B36305";

private int getFactorColor(int color, float factor) {
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
hsv[2] *= factor;
color = Color.HSVToColor(hsv);
return color;

public void onCreate(Bundle savedInstanceState) {


ActionBar actionBar = getSupportActionBar();
if(actionBar != null) {
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor(actionBarColor)));


What the warning is telling you is that actionBarColor shouldn't be a global variable (i.e. a field), because it's only used in one method (onCreate). This is good advice: you should always minimize the scope of your variables, because it improves readability and reduces possibilities for programming errors.

To get rid of the warning, fix the problem by declaring the variable within onCreate:

final String actionBarColor = "#B36305";

if(actionBar != null) {
        new ColorDrawable(Color.parseColor(actionBarColor)));