ChatGPT解决这个技术问题 Extra ChatGPT

如何在 android strings.xml 中写入字符 &

我在 strings.xml 文件中写了以下内容:

<string name="game_settings_dragNDropMove_checkBox">Move by Drag&Drop</string>

我收到以下错误:

The reference to entity "Drop" must end with the ';' delimiter.

如何在 strings.xml 中写入字符 &?

在 android studio 中,您只需按 Alt+Enter,它就会为您转换。

B
Bob Fincheimer

对其进行编码:

&amp;

如果使用 CDATA,请注意某些字符是保留的。 © -> &复制;参考这篇文章。 w3schools.com/html/html_entities.asp
\u0026 最好按照@Moss 的建议使用 unicode
M
Moss

对于特殊字符,我通常使用 Unicode 定义,对于 '&'例如: \u0026 如果我是正确的。这是一个不错的参考页面:http://jrgraphix.net/research/unicode_blocks.php?block=0


这个似乎效果最好。 $amp;来自 getString() 没有被转换。所以这是一种痛苦。
对于某些符号,这对我不起作用,例如 \u227A。
对于 Ⓡ 符号使用 ®和商标™符号 ™
M
Mobile Developer iOS Android

这是我的问题,我的解决方案如下:将 &gt; 用于 >&lt; 用于 <&amp; 用于 &"'" 用于 '&quot 用于 { 10}


无法编辑此内容,因为更改很小,而是留下评论。它应该是 Use &gt; for >, &lt;for <
K
Khemraj Sharma

即使你的问题得到了回答,我仍然想告诉更多这样的实体。这些是 html entities,所以在 android 中你可以这样写:

下面替换为:

& with &amp;
> with &gt;
< with &lt;
" with &quot;, &ldquo; or &rdquo;
' with &apos;, &lsquo; or &rsquo;
} with &#125;

f
faruk

它应该是这样的:

<string name="game_settings_dragNDropMove_checkBox">Move by Drag&amp;Drop</string>

c
caulitomaz

也可以将字符串的内容放入 XML CDATA,就像 Android Studio 在您Extract string resource时为您所做的那样

<string name="game_settings_dragNDropMove_checkBox"><![CDATA[Move by Drag&Drop]]></string>


r
ralphgabb

这可能很老了。但是对于那些寻找快速代码的人。

 public String handleEscapeCharacter( String str ) {
    String[] escapeCharacters = { "&gt;", "&lt;", "&amp;", "&quot;", "&apos;" };
    String[] onReadableCharacter = {">", "<", "&", "\"\"", "'"};
    for (int i = 0; i < escapeCharacters.length; i++) {
        str = str.replace(escapeCharacters[i], onReadableCharacter[i]);
    } return str;
 }

处理转义字符,您可以在它们各自的数组上添加字符和符号。

-干杯


G
Gowthaman M

为避免该错误,请使用提取字符串:

<string name="travels_tours_pvt_ltd"><![CDATA[Travels & Tours (Pvt) Ltd.]]></string>

G
Ghayas

& 在字符串中,如:

<string name="string_abc">Translate &amp; Scan Objects</string>

输出将是:

翻译和扫描对象


G
Gowthaman M

你可以这样写

<string name="you_me">You &#38; Me<string>

输出:你和我


M
MetaPlanet

Mac 和 Android 工作室用户:

输入您的字符,例如 &在 string.xml 或布局中并选择“选项”和“返回”键。 Please refer the screen shot


M
Mubarak Tahir

如果你想直接硬编码xml中的字符串,你可以这样加起来。

  <TextView 
     android:layout_marginStart="5dp"
     android:layout_marginLeft="5dp"
     android:layout_centerVertical="true"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="You &amp; Me"

u
user3194684

我发现的最简单的方法是将“&”替换为 Unicode 等价物。所以对于给定的例子写:

<string name="game_settings_dragNDropMove_checkBox">Move by Drag\u0026Drop</string>

u
user3194684

我发布这个是因为上述编码都不适合我。

我发现用序列替换 & 符号:&#38; 用作 xml 字符串资源。如:

<string name="webLink"><a href="https://www.example.com?param1=option1&#38;param2=option2">click here</a></string>