You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android:调用SharedPreferences.Editor的commit()时如何正确抑制指定Lint警告

精准抑制SharedPreferences commit()的Lint警告

刚好踩过这个坑!你完全不用依赖过于宽泛的@SuppressWarnings("all"),有更精准的注解值可以针对性地屏蔽这个特定的Lint警告。

具体的警告ID

这个提示你"Consider using apply instead..."的Lint检查,对应的唯一ID是CommitPrefEdits。你只需要在方法签名前添加这个精准的注解就能只屏蔽该警告,不会影响其他Lint检查的生效。

代码示例(Java)

@SuppressWarnings("CommitPrefEdits")
private void saveUserPreference() {
    SharedPreferences.Editor editor = getSharedPreferences("app_settings", MODE_PRIVATE).edit();
    editor.putBoolean("is_first_launch", false);
    editor.commit(); // 此处不再触发Lint警告
}

代码示例(Kotlin)

如果你用Kotlin,写法类似,只是注解换成@Suppress:

@Suppress("CommitPrefEdits")
fun saveUserPreference() {
    val editor = getSharedPreferences("app_settings", MODE_PRIVATE).edit()
    editor.putBoolean("is_first_launch", false)
    editor.commit()
}

怎么找到其他Lint警告的精准ID?

顺便提一下,以后遇到类似的Lint警告,都可以用这个方法找精准ID:

  • 在Android Studio中,把鼠标悬停在警告提示上,弹出的详情框里会显示Id: XXXX的字段;
  • 或者打开Lint的问题面板(底部的"Problems"标签),点击对应的警告,右侧的详细信息里也能找到对应的ID。

这样就不用再用"all"这种一刀切的方式,既能保留其他有用的Lint检查,又能屏蔽你确实不需要的特定警告。

内容的提问来源于stack exchange,提问作者Boycott A.I.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:13:48