Android:如何使用名称从资源中获取字符串?

发布于 2024-12-06 01:59:41 字数 1024 浏览 0 评论 0 原文

我希望在我的资源文件 res\values\strings.xml 中为 UI 提供两种语言并为它们提供单独的字符串值:

<string name="tab_Books_en">Books</string>
<string name="tab_Quotes_en">Quotes</string>
<string name="tab_Questions_en">Questions</string>
<string name="tab_Notes_en">Notes</string>
<string name="tab_Bookmarks_en">Bookmarks</string>

<string name="tab_Books_ru">Книги</string>
<string name="tab_Quotes_ru">Цитаты</string>
<string name="tab_Questions_ru">Вопросы</string>
<string name="tab_Notes_ru">Заметки</string>
<string name="tab_Bookmarks_ru">Закладки</string>

现在我需要在我的应用程序中动态检索这些值:

spec.setContent(R.id.tabPage1);
String pack = getPackageName();
String id = "tab_Books_" + Central.lang;
int i = Central.Res.getIdentifier(id, "string", pack);
String str = Central.Res.getString(i);

我的问题是 i = 0

为什么它在我的情况下不起作用?

I would like to have 2 languages for the UI and separate string values for them in my resource file res\values\strings.xml:

<string name="tab_Books_en">Books</string>
<string name="tab_Quotes_en">Quotes</string>
<string name="tab_Questions_en">Questions</string>
<string name="tab_Notes_en">Notes</string>
<string name="tab_Bookmarks_en">Bookmarks</string>

<string name="tab_Books_ru">Книги</string>
<string name="tab_Quotes_ru">Цитаты</string>
<string name="tab_Questions_ru">Вопросы</string>
<string name="tab_Notes_ru">Заметки</string>
<string name="tab_Bookmarks_ru">Закладки</string>

Now I need to retrieve these values dynamically in my app:

spec.setContent(R.id.tabPage1);
String pack = getPackageName();
String id = "tab_Books_" + Central.lang;
int i = Central.Res.getIdentifier(id, "string", pack);
String str = Central.Res.getString(i);

My problem is that i = 0.

Why does not it work in my case?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

杀手六號 2024-12-13 01:59:41

您所指的链接似乎适用于运行时生成的字符串。 strings.xml 中的字符串不是在运行时创建的。
您可以通过 getResources() 获取它们,

String mystring = getResources().getString(R.string.mystring);

它是 Context 类的一个方法。如果您位于 ActivityService(扩展了 Context)中,您可以像此代码片段中那样使用它。

另外请注意,整个语言依赖关系可以由 android 框架来处理
只需为每种语言创建不同的文件夹即可。如果英语是您的默认语言,只需将英语字符串放入 res/values/strings.xml 中即可。然后创建一个新文件夹 values-ru 并将同名的俄语字符串放入 res/values-ru/strings.xml 中。从这一点开始,当您调用 getString() 或通过 @string/mystring 引用 XML 中的字符串时,Android 会根据您的设备区域设置选择正确的字符串。
来自 res/values/strings.xml 的值是后备值,如果您没有覆盖用户区域设置的文件夹,则该值将用作默认值。

请参阅本地化提供资源了解更多信息。

The link you are referring to seems to work with strings generated at runtime. The strings from strings.xml are not created at runtime.
You can get them via

String mystring = getResources().getString(R.string.mystring);

getResources() is a method of the Context class. If you are inside a Activity or a Service (which extend Context) you can use it like in this snippet.

Also note that the whole language dependency can be taken care of by the android framework.
Simply create different folders for each language. If english is your default language, just put the english strings into res/values/strings.xml. Then create a new folder values-ru and put the russian strings with identical names into res/values-ru/strings.xml. From this point on android selects the correct one depending on the device locale for you, either when you call getString() or when referencing strings in XML via @string/mystring.
The ones from res/values/strings.xml are the fallback ones, if you don't have a folder covering the users locale, this one will be used as default values.

See Localization and Providing Resources for more information.

時窥 2024-12-13 01:59:41

验证您的 packageName 是否正确。您必须参考 Android 应用程序的根包。

private String getStringResourceByName(String aString) {
      String packageName = getPackageName();
      int resId = getResources().getIdentifier(aString, "string", packageName);
      return getString(resId);
    }

Verify if your packageName is correct. You have to refer for the root package of your Android application.

private String getStringResourceByName(String aString) {
      String packageName = getPackageName();
      int resId = getResources().getIdentifier(aString, "string", packageName);
      return getString(resId);
    }
≈。彩虹 2024-12-13 01:59:41

不仅仅来自活动:

public static String getStringByIdName(Context context, String idName) {
    Resources res = context.getResources();
    return res.getString(res.getIdentifier(idName, "string", context.getPackageName()));
}

Not from activities only:

public static String getStringByIdName(Context context, String idName) {
    Resources res = context.getResources();
    return res.getString(res.getIdentifier(idName, "string", context.getPackageName()));
}
屋檐 2024-12-13 01:59:41
getResources().getString(getResources().getIdentifier("propertyName", "string", getPackageName()))
getResources().getString(getResources().getIdentifier("propertyName", "string", getPackageName()))
淡淡の花香 2024-12-13 01:59:41

我会在 leonvian 的解决方案中添加一些内容,因此如果万一在资源中找不到该字符串(返回值 0,这不是有效的资源代码),该函数可能会返回一些内容:

private String getStringResourceByName(String aString) {
    String packageName = getPackageName();
    int resId = getResources()
            .getIdentifier(aString, "string", packageName);
    if (resId == 0) {
        return aString;
    } else {
        return getString(resId);
    }
}

I would add something to the solution of leonvian, so if by any chance the string is not found among the resources (return value 0, that is not a valid resource code), the function might return something :

private String getStringResourceByName(String aString) {
    String packageName = getPackageName();
    int resId = getResources()
            .getIdentifier(aString, "string", packageName);
    if (resId == 0) {
        return aString;
    } else {
        return getString(resId);
    }
}
九局 2024-12-13 01:59:41

最佳方法

App.getRes().getString(R.string.some_id)

将在任何地方工作(Utils,模型也)。

我已经阅读了所有答案,所有答案都可以帮助你完成工作。

  • 您可以在 ActivityFragment 中使用 getString(R.string.some_string_id) >。
  • 您可以在无法直接访问 getString() 方法的情况下使用 Context.getString(R.string.some_string_id) 。就像对话框一样。

出现问题

您没有Context访问

,例如Util类中的方法。假设下面的方法没有上下文。

public void someMethod(){
    ...
    // can't use getResource() or getString() without Context.
}

现在,您将在此方法中将 Context 作为参数传递,并使用 getString()。

public void someMethod(Context context){
    ...
    context.getString(R.string.some_id);
}

我做什么

public void someMethod(){
    ...
    App.getAppResources().getString(R.string.some_id)
}

什么?在应用程序的任何地方使用都非常简单!

因此,这里有一个解决方案,您可以通过它从任何地方访问资源,例如 Util class

import android.app.Application;
import android.content.res.Resources;

public class App extends Application {
    private static Resources resources;

    @Override
    public void onCreate() {
        super.onCreate();

        resources = getResources();
    }

    public static Resources getAppResources() {
        return resources;
    }

}

将名称字段添加到 manifest.xml 标记中。

<application
        android:name=".App"
        ...
        >
        ...
    </application>

现在你可以走了。在应用程序中的任何位置使用 App.getAppResources().getString(R.string.some_id)

Best Approach

App.getRes().getString(R.string.some_id)

Will work Everywhere (Utils, Models also).

I have read all the answers, all answers can make your work done.

  • You can use getString(R.string.some_string_id) in both Activity or Fragment.
  • You can use Context.getString(R.string.some_string_id) where you don't have direct access to getString() method. Like Dialog.

Problem

When you don't have Context access, like a method in your Util class.

Assume below method without Context.

public void someMethod(){
    ...
    // can't use getResource() or getString() without Context.
}

Now you will pass Context as a parameter in this method and use getString().

public void someMethod(Context context){
    ...
    context.getString(R.string.some_id);
}

What i do is

public void someMethod(){
    ...
    App.getAppResources().getString(R.string.some_id)
}

What? It is very simple to use anywhere in your app!

So here is a solution by which you can access resources from anywhere like Util class .

import android.app.Application;
import android.content.res.Resources;

public class App extends Application {
    private static Resources resources;

    @Override
    public void onCreate() {
        super.onCreate();

        resources = getResources();
    }

    public static Resources getAppResources() {
        return resources;
    }

}

Add name field to your manifest.xml <application tag.

<application
        android:name=".App"
        ...
        >
        ...
    </application>

Now you are good to go. Use App.getAppResources().getString(R.string.some_id) anywhere in app.

东北女汉子 2024-12-13 01:59:41

更简单的方法是在活动中使用 getString() 函数。

String myString = getString(R.string.mystring);

参考:http://developer.android.com/guide/topics/resources /string-resource.html

我认为这个功能是在最近的Android版本中添加的,任何了解历史的人都可以评论这一点。

Easier way is to use the getString() function within the activity.

String myString = getString(R.string.mystring);

Reference: http://developer.android.com/guide/topics/resources/string-resource.html

I think this feature is added in a recent Android version, anyone who knows the history can comment on this.

怎樣才叫好 2024-12-13 01:59:41

getResources() 仅当您位于 ActivityFragment 类中时才有效。

  • 要访问任何地方的字符串资源,

请使用:

Resources.getSystem().getString(android.R.string.somecommonstuff)

getResources() works only when you're in Activity or Fragment class.

  • to get access to strings resource everywhere,

use:

Resources.getSystem().getString(android.R.string.somecommonstuff)
皇甫轩 2024-12-13 01:59:41

如果您使用 Kotlin,您可以按如下方式定义扩展函数:

fun Context.getStringResourceByName(stringName: String): String? {
    val resId = resources.getIdentifier(stringName, "string", packageName)
    return getString(resId)
}

然后简单地使用它。例如,在 Puzzles 应用程序中,我根据图像文件名设置活动标题:

val stringName = "${folderName}_${assetName.substringBefore(".")}"
title = getStringResourceByName(stringName)

在本例中,我根据动态名称读取字符串资源。

In case you are using Kotlin, you can define an extension function as follows:

fun Context.getStringResourceByName(stringName: String): String? {
    val resId = resources.getIdentifier(stringName, "string", packageName)
    return getString(resId)
}

And then simply use it. For example, in a Puzzles app I set the Activity title according to the image file name:

val stringName = "${folderName}_${assetName.substringBefore(".")}"
title = getStringResourceByName(stringName)

In this example I am reading string resources based on dynamic names.

宫墨修音 2024-12-13 01:59:41

如果您没有 Activity 引用,您可以通过以下方式使用上下文:

getContext().getString(R.string.your_string_name);

If you don't have an Activity reference, you can use your context in this way:

getContext().getString(R.string.your_string_name);
痴梦一场 2024-12-13 01:59:41

如果您想在 Activity 或 Fragmnet 内部获取它,那么:

getContext().getResources().getString(R.string.string_name);

如果您想从 Activity 或 Fragmnet 之外的类获取它,而您没有 Activity 上下文,则使用应用程序上下文:

getApplicationContext().getResources().getString(R.string.string_name);

If you wannt get it inside an activity or fragmnet, then:

getContext().getResources().getString(R.string.string_name);

If you want to get it from a class outside of activity or fragment where you don't have the activity context then use application context:

getApplicationContext().getResources().getString(R.string.string_name);
久隐师 2024-12-13 01:59:41

在 Kotlin 中,利用扩展函数

In Kotlin, Leverage Extension functions ????

fun Context.getStringByName(name: String): String {
    return getString(resources.getIdentifier(name, "string", packageName))
}
︶葆Ⅱㄣ 2024-12-13 01:59:41

还有一组预定义的 Android 字符串,例如“Ok”、“Cancel”和许多其他字符串 - 因此您不必全部声明。它们只需通过以下方式即可获得:(

getString(android.R.string.ok)

在本例中为“Ok”字符串)。顺便说一句,还有其他可用的 Android 资源,例如图标图像等。

There is also a set of predefined Android strings such as "Ok", "Cancel" and many others - so you don't have to declare all. They're available simply by:

getString(android.R.string.ok)

(In this case, "Ok" string). BTW there are also other Android resources available like for example icons images etc.

油焖大侠 2024-12-13 01:59:41

String myString = getString(R.string.mystring);

简单的方法

String myString = getString(R.string.mystring);

easy way

琴流音 2024-12-13 01:59:41

您可以在活动中尝试此操作:

getResources().getString(R.string.your string name);

在其他情况下,例如片段,...使用

getContext().getResources().getString(R.string.your string name);

You can try this in an Activity:

getResources().getString(R.string.your string name);

In other situations like fragments,... use

getContext().getResources().getString(R.string.your string name);
国产ˉ祖宗 2024-12-13 01:59:41

为了安全起见,您应该添加:
mContext.getResources().getString(R.string.your_string);

mContext可以是:Fragment的onAttach()中的context或者Activity的this。

To safe, you should add:
mContext.getResources().getString(R.string.your_string);

mContext can be: context in onAttach() of Fragment or this of Activity.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文