【问题标题】:How to fix Lint's "[deprecation] locale in Configuration has been deprecated" warning如何修复 Lint 的“[deprecation] 配置中的语言环境已被弃用”警告
【发布时间】:2018-08-19 12:12:10
【问题描述】:

希望这不是关于语言环境已弃用 context.getResources().getConfiguration().locale 调用的许多其他问题的重复,因为我已经修复了它。

我将如何摆脱以下代码的 Lint 警告:

public static String toDateString(Context context, Date date)
{
    DateFormat format = Build.VERSION.SDK_INT >= 24 ?
            DateFormat.getDateInstance(DateFormat.MEDIUM, context.getResources().getConfiguration().getLocales().get(0)) :
            DateFormat.getDateInstance(DateFormat.MEDIUM, context.getResources().getConfiguration().locale);
    return format.format(date);
}

【问题讨论】:

    标签: android locale deprecated lint android-7.0-nougat


    【解决方案1】:

    你不应该直接使用属性。

    getLocales

    【讨论】:

    • 这就是我为 API >=24 所做的。从您的链接:“如果只需要主要语言环境,getLocales().get(0) 现在是首选访问器。”
    • 我的意思是我没有直接使用它
    • @PIXP 我注意到了第二个分支:DateFormat.getDateInstance(DateFormat.MEDIUM, context.getResources().getConfiguration().locale);直接使用属性
    【解决方案2】:

    首先检查您当前的版本并使用已弃用的版本。试试这个,

        Locale locale;
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
          locale = this.getResources().getConfiguration().getLocales().get(0);
        } else{
          locale = this.getResources().getConfiguration().locale;
        }
    
    1. 你可以使用Locale.getDefault()

    【讨论】:

    • 您的第一个解决方案与我的代码相同。我现在正在检查第二个。
    • 你可以试试这个Resources resources = context.getResources(); Locale locale = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ? resources.getConfiguration().getLocales() .getFirstMatch(resources.getAssets().getLocales()) : resources.getConfiguration().locale;
    猜你喜欢
    • 2022-10-21
    • 1970-01-01
    • 1970-01-01
    • 2015-12-25
    • 2013-02-23
    • 2022-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多