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

时光怂恿深爱的人放手 提交于 2019-12-18 11:05:05

问题


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)));
        }
    }
}

回答1:


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) {
    actionBar.setBackgroundDrawable(
        new ColorDrawable(Color.parseColor(actionBarColor)));
}



回答2:


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

@SuppressWarnings("FieldCanBeLocal")




回答3:


This is not a error this is waring when you go in the lint errors than it will show in class level variable which used as a local variable. Go and just define it as a local variable. It will Works

For example -

private Tracker mTracker, mTracker2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    GoogleAnalytics mInstance = GoogleAnalytics.getInstance(this);
    mTracker = mInstance.getDefaultTracker();
    mTracker2 = mInstance.getTracker(URL.ANALYTIC);
    mInstance.setDefaultTracker(mTracker2);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.actress_about_detail);
}

we use mtracker variable as a local so we have to declare in oncreate method. This will resolve your error.

Hope this will help you.



来源:https://stackoverflow.com/questions/31713073/field-can-be-converted-to-a-local-variable-message-appearing-when-setting-andr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!