Android 将变量用作名称strings.xml

Android 将变量用作名称strings.xml,android,data-binding,Android,Data Binding,我有一些状态为的包。 在xml字符串中,这些状态将是(翻译成挪威语) 因此字符串名称将与文本匹配。我还使用数据绑定来获取parcelitem.status 我的问题是它只是打印出“@strings/transport\u to\u receipent”,而不是实际的翻译。有没有一种聪明的方法可以做到这一点,或者我应该在上面做一个方法吗?您需要使用以下类似的方法来获得: android:text="@{`@strings/`+ parcelListItem.status.toString

我有一些状态为的包。 在xml字符串中,这些状态将是(翻译成挪威语)

因此字符串名称将与文本匹配。我还使用数据绑定来获取parcelitem.status


我的问题是它只是打印出
“@strings/transport\u to\u receipent”
,而不是实际的翻译。有没有一种聪明的方法可以做到这一点,或者我应该在上面做一个方法吗?

您需要使用以下类似的方法来获得:

android:text="@{`@strings/`+ parcelListItem.status.toString()}"
public String getStringByString(String key) {
    String retString = key;
    int id = getResource().getIdentifier(key, "string", getPackageName());
    if (id != 0) {
        retString = getString(id);
    }

    return retString;
}
Utils.getStringResourceIdByName(context, parcelListItem.status.toString())

因此,基本上,这将尝试从strings.xml文件中获取资源名称。如果失败,将返回密钥。

要访问此字符串
Leveres i dag
您需要像这样更新资源配置

Resources resources= context.getResources();
Configuration configuration = resources.getConfiguration();
DisplayMetrics metrics= resources.getDisplayMetrics();
configuration.setLocale(new Locale("nb")); //country code depend on your XML
resources.updateConfiguration(configuration,metrics);
nb
是国家代码,在您的情况下可能会有所不同。
您将在
Resource
文件夹中的
string.xml
文件侧显示国家代码。

根据上述答案使用此方法:

public static int getStringResourceIdByName(Context context, String stringId) {
    if (Utils.isNullOrBlank(stringId))
        stringId = ParcelListItem.Status.unknown.toString();
    return context.getResources().getIdentifier(stringId, "string", context.getPackageName());
}
是这样说的:

android:text="@{`@strings/`+ parcelListItem.status.toString()}"
public String getStringByString(String key) {
    String retString = key;
    int id = getResource().getIdentifier(key, "string", getPackageName());
    if (id != 0) {
        retString = getString(id);
    }

    return retString;
}
Utils.getStringResourceIdByName(context, parcelListItem.status.toString())

您的应用程序中是否有双语支持?哪种语言是默认语言?默认语言是英语此
字符串属于
挪威XML
?是的,它属于挪威XML