【问题标题】:Reference to standard Android strings in XML在 XML 中引用标准 Android 字符串
【发布时间】:2016-11-16 15:54:39
【问题描述】:

在我的 Java 代码中,我可以轻松访问标准的 Android 字符串,例如“save”、“ok”、“cancel”等。在一个活动中,我可以这样做: getString(android.R.string.cancel)

我想从 XML 文件中访问这些字符串。我尝试过android:text="@android:string/cancel 之类的方法,但这似乎不起作用。有没有办法在 XML 中使用这些字符串?

【问题讨论】:

  • “这似乎行不通”——嗯……我希望它行得通。您的具体症状是什么?
  • @CommonsWare:Android 工作室说Cannot resolve symbol。它会自动完成android: 部分,但在编写string/ 部分时,它不再显示任何工具提示。
  • 使用@string/cancel
  • @Marcel50506 这是个谜。对我也很好。尝试干净的构建。还要确保 xml 中没有其他错误。
  • 不知何故我今天不能再重现这个问题了。一定是一个干净的构建情况,虽然我昨天试过了。感谢您的帮助!

标签: java android xml string


【解决方案1】:

我无法重现您的问题。使用 Android Studio 2.2.2,我刚刚从新项目向导创建了一个新项目,选择“空活动”作为模板并取消选中 appcompat 选项。然后,在activity_main.xml 中,我更改了TextView 以引用您想要的字符串:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/activity_main"
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:paddingBottom="@dimen/activity_vertical_margin"
  android:paddingLeft="@dimen/activity_horizontal_margin"
  android:paddingRight="@dimen/activity_horizontal_margin"
  android:paddingTop="@dimen/activity_vertical_margin"
  tools:context="com.commonsware.myapplication.MainActivity">

  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@android:string/cancel" />
</RelativeLayout>

这可以干净地构建并在 Android 7.1 上运行。

由于该字符串自 API 级别 1 起就已包含在 SDK 中,因此我预计在使用它时不会出现任何问题。

【讨论】:

    【解决方案2】:

    试试 android:text="@string/cancel"

    【讨论】:

      猜你喜欢
      • 2011-02-21
      • 2013-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-08
      • 1970-01-01
      • 1970-01-01
      • 2017-07-27
      相关资源
      最近更新 更多