"Field can be converted to a local variable" message appearing when setting Android ActionBar colour

Swarthy46 picture Swarthy46 · Jul 30, 2015 · Viewed 41.5k times · Source

After setting the colour of the Action Bar, actionBarColor in 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;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.fragment_activity_main);

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

Answer

If you know you will use the variable(s), add to the top of your class:

@SuppressWarnings("FieldCanBeLocal")