有没有办法抑制布局文件中“硬编码字符串”的警告?

30

有没有一种方法可以消除布局文件中关于硬编码字符串的个别警告?

我经常在TextView中放置占位文本,以便在设计时查看它们。这样做的缺点是会收到大量关于硬编码字符串的警告。但如果没有这些警告,我就无法在布局中看到TextView。


我理解使用 strings.xml 的原则,但有时你知道你只使用该字符串一次。 - Jacksonkr
1
好问题。似乎最好有一些转义字符来允许文本作为占位符,例如"<用户名称在此处>"。 - Daniel
4个回答

36

您可以将以下内容添加到文本视图元素中:

tools:ignore="HardcodedText"

示例:

    <TextView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is a hardcoded text"
        tools:ignore="HardcodedText" />

请注意,Eclipse中有一个快捷方式可以轻松添加此内容:只需按下CTRL + 1并选择相关选项。

不幸的是,我找不到一种方法来对整个布局执行此操作,您将需要为每个元素执行此操作。

请注意,您还必须将xmlns:tools="http://schemas.android.com/tools属性添加到根元素中。


这就是我想要的。我不想忽略所有的Android Lint警告。它们确实很有用,但有时会让我发疯,因为我已经知道了,也不需要它 :) - Jacob Dam
4
请注意,您还必须将“xmlns:tools =”http://schemas.android.com/tools“”属性添加到根元素中,否则您将收到类似“解析XML时出错:未绑定前缀”的错误。 - Adam Rosenfield
完美的解决方案,简短、简单而且甜美。谢谢! - SMBiggs
要使其适用于整个布局,您需要将其包含在父视图中。 - Infinite Loops

31
另一种方法是使用tools:text而不是android:text

另一种方法是使用tools:text而不是 android:text

<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    tools:text="This is a hardcoded text" />
请注意,您还必须将xmlns:tools="http://schemas.android.com/tools属性添加到根元素。

2
我认为这比 tools:ignore="HardcodedText" 更好,因为预览实际上会显示它。 - Shine
1
哇,我不知道那个,太棒了。 - Redwarp
1
我喜欢这个答案,但代码检查工具抱怨 tools:text 也被硬编码了,这是很荒谬的,因为它只是示例文本,不会编译到应用程序中...似乎没有关闭它的办法... - Andrew
@Andrew,我没有收到任何代码检查错误,可能是因为工具的版本较新。 - ThomasW
1
该方法会使文本从设计预览中消失。 - Infinite Loops
显示剩余2条评论

19
在Eclipse中,进入“窗口”->“首选项”->“Android”->“Lint错误检查”。
向下滚动并选择“Hardcoded Text”(在国际化下)。 在严重性下拉框中,选择“忽略”并单击“应用”。

3
对于Android Studio也是相似的。偏好设置 -> Android -> Lint -> 国际化 -> "硬编码文本" 和 "文本国际化"。我也会为toast切换这些开关。 - Diesel

1

使用 string.xml 文件来消除此警告...

您需要将字符串放入 string.xml 文件中,然后像这样设置 android:text="@string/mytext"

res-->value->string.xml 中添加 <string name="mytext">Your Text</string>

http://tools.android.com/tips/lint


好的链接,以前从未注意过Android工具网站..看起来那里有一些有用的信息。 - ycomp
谢谢您的建议,但这会给我带来更多问题,而不是解决问题... 我喜欢保持字符串文件相对干净。 - ycomp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接