“字段可以转换为局部变量”。设置Android ActionBar颜色时出现错误消息 [英] "Field can be converted to a local variable" message appearing when setting Android ActionBar colour

查看:882
本文介绍了“字段可以转换为局部变量”。设置Android ActionBar颜色时出现错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在设置操作栏的颜色后,中的 actionBarColor 私有字符串actionBarColor =#B36305; 获取突出显示黄色,并出于某种原因返回警告。可以做些什么来消除这个警告?

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


推荐答案

警告告诉你的是 actionBarColor 不应该是全局变量(即字段),因为它只在一个方法中使用(的onCreate )。这是一个很好的建议:你应该总是最小化变量的范围,因为它提高了可读性并减少了编程错误的可能性。

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.

要摆脱警告,修复通过在 onCreate 中声明变量来解决问题:

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

这篇关于“字段可以转换为局部变量”。设置Android ActionBar颜色时出现错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆