是否可以在布局文件中连接资源字符串/字符串连接?

Nit*_*ish 5 xml layout android

我有资源字符串:

<string name="address">Address</string>
<string name="city">City</string>
<string name="country">Country</string>
<string name="pincode">Pincode</string>  
Run Code Online (Sandbox Code Playgroud)

在我的应用程序中,我在很少的地方单独使用这些字符串,在很少的地方我用冒号接替它们.
我不知道要创建另外四个资源字符串:

<string name="address_with_colon">Address: </string>
<string name="city_with_colon">City: </string>
<string name="country_with_colon">Country: </string>
<string name="pincode_with_colon">Pincode: </string>  
Run Code Online (Sandbox Code Playgroud)

现在要实现这一点,我必须用冒号连接我的资源字符串.我知道这很简单,虽然我可以在我的活动类中编写java代码.但我想要的是在我的布局文件中进行连接.
问题:布局文件中是否可以进行字符串连接?
这是我必须执行连接的地方:

android:text="concatenation_if_possible"
Run Code Online (Sandbox Code Playgroud)

And*_*rew 5

使用 XML 实体,可以在 XML 文件中的多个位置使用相同的字符串:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE resources [
  <!ENTITY appname "MrQuery">
  <!ENTITY author "Oded">
]>

<resources>
    <string name="app_name">&appname;</string>
    <string name="description">The &appname; app was created by &author;</string>
</resources>
Run Code Online (Sandbox Code Playgroud)

我使用了这个答案:dynamic String using String.xml?


小智 3

\n

问题:布局文件中可以进行字符串连接吗?

\n
\n\n

据我所知没有。

\n\n

一种解决方案是使用@DIVA 之前回答过的内容。

\n\n

另一种可能的解决方案是创建一个扩展 TextView 的自定义视图(或您想要实现此目的的视图),并创建一个接收custom:concatenate字符串引用并自动执行连接的自定义属性。恕我直言,我认为这是最干净的方法。

\n\n

在代码中将如下所示:

\n\n
<com.whatever.ConcatenateTextView\n    android:text="@string/whatever"\n    custom:concatenate="@string/second_string"/>\n
Run Code Online (Sandbox Code Playgroud)\n\n

或者\xe2\x80\xa6,您可以使用 Drawables 的强大功能创建自定义 TextDrawable (@Devunwired 在这篇文章中对此进行了很好的解释,并在Github中具体实现了它)。

\n\n

复制 @Devunwired 在他的帖子中所说的内容:

\n\n
\n

有了这个类,文本现在可以成为 Drawable 世界的一部分,这意味着它不仅可以单独设置在通常放置图像的位置,还可以与 StateListDrawable 等容器中的其他 Drawable 一起放置,或者使用类似的动画TransitionDrawable 和 ClipDrawable。在许多情况下,我们可以使用它来完成原本需要多个视图或复合控件才能实现给定视觉效果的工作;因此它可以减少视图层次结构的开销。

\n
\n\n

这与我之前解释的自定义 TextView(或您想要使用的任何视图)相结合,为您提供了一个非常强大的选项。再次复制@Devunwired 在他的帖子中写的示例:

\n\n
ImageView mImageOne;\nTextDrawable d = new TextDrawable(this);\nd.setText("SAMPLE TEXT\\nLINE TWO");\nd.setTextAlign(Layout.Alignment.ALIGN_CENTER);\n\nmImageOne.setImageDrawable(d);\n
Run Code Online (Sandbox Code Playgroud)\n\n

如果您需要更多帮助,请在评论中告诉我,我很乐意更新答案!

\n