【问题标题】:How to allow hard coded strings and stop asking about using strings.xml如何允许硬编码字符串并停止询问使用 strings.xml
【发布时间】:2016-04-06 08:03:17
【问题描述】:

我目前正在开发一个 android 项目,我没有计划将它翻译成其他语言,所以我没有将字符串文字保存在 strings.xml 中。但是,每次我硬编码字符串文字时,Android Studio 都会不断抱怨,尤其是在为 TextView 设置文本值时。

有没有办法禁用这些警告?

【问题讨论】:

    标签: android string android-studio


    【解决方案1】:

    你可以在以下位置编辑它 Settings->Editor->Inspections->Android Lint->TextView Internationalization:

    对于 xml Settings->Editor->Inspections->Android Lint->Hardcoded Text:

    【讨论】:

    • 它从 java 类中删除警告,我如何也从布局 xml 中删除警告?
    • 完美,现在都消失了
    【解决方案2】:

    在我看来,最好的方法是使用 gradle 文件,这将允许您在全局范围内抑制这些,而不必在 Android Studio 中进行,因此您的设置也可以进入源代码控制,然后您不必单独装饰要应用警告的每个方法。为此,请在您的 gradle 文件 lint 选项中禁用 SetTextI18n,如下所示:

    android {
        lintOptions{
            disable 'SetTextI18n'
        }
    }
    

    Gradle 同步,瞧,警告消失了。

    【讨论】:

      【解决方案3】:

      添加

      @SuppressLint("SetTextI18n")
      

      在您的功能之上。 示例:

      @SuppressLint("SetTextI18n")
      private void updateEZWBMode2ConnectionStatus(){
          switch (IsConnected.checkMode2(mContext)){
              case IsConnected.USB_TETHERING:
                  M2StatusTV.setText("Status: Connected");
                  M2StatusTV.setTextColor(Color.argb(255,0,255,0));
                  M2ReceiveTV.setVisibility(View.VISIBLE);
                  startTestReceiverSafe(M2ReceiveTV);
                  break;
              case IsConnected.USB_CONNECTED:
                  M2StatusTV.setText("Status: No Tethering");
                  M2StatusTV.setTextColor(Color.argb(255,255,51,51));
                  M1ReceiveTV.setVisibility(View.GONE);
                  M2ReceiveTV.setVisibility(View.GONE);
                  stopTestReceiverSafe();
                  break;
              case IsConnected.USB_NOTHING:
                  M2StatusTV.setText("Status: No USB Connection");
                  M2StatusTV.setTextColor(Color.argb(255,255,51,51));
                  M1ReceiveTV.setVisibility(View.GONE);
                  M2ReceiveTV.setVisibility(View.GONE);
                  stopTestReceiverSafe();
                  break;
          }
      }
      

      【讨论】:

        【解决方案4】:

        老问题,但无论如何接受的答案是误导性的。

        无需翻译字符串文字资源。实际上,它们可以是资源文件中的marked as non-translatable。这样一来,您仍会坚持使用 best practices,而不会被 lint 和翻译所困扰。

        <string name="invite_sent" translatable="false">Invite sent</string>
        

        虽然禁用 Lint 有助于停止烦恼,但您想要(并且应该)使用字符串文字资源还有另一个原因:重复。遵循 DRY (Don't Repeat Yourself) 原则可以避免一系列问题,从复杂的重构到意外行为,以及用户在使用应用程序时体验的不一致。试想一下,“确定”按钮出现在 10 多个屏幕中。拥有单一的参考和来源可以简化和集中项目的维护。

        【讨论】:

          猜你喜欢
          • 2021-08-21
          • 1970-01-01
          • 2014-09-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-11-25
          • 1970-01-01
          相关资源
          最近更新 更多