java 如何在 Android 中从枚举的 ToString 访问资源字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12625041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 09:36:36  来源:igfitidea点击:

How to access resource strings from enum's ToString in Android?

javaandroid

提问by fortyCakes

In my app, I have a Spinner being filled from an enum:

在我的应用程序中,我有一个从枚举中填充的 Spinner:

ArrayAdapter<myEnum> enumAdapter = new ArrayAdapter<Stroke> (parentActivity.getApplicationContext(), R.layout.simple_spinner_item, myEnum.values());
enumAdapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
enumSpinner.setAdapter(strokeAdapter);

This uses an override of the enum's toString()method to get a friendly name for the enum values to display in the Spinner. Currently my enum has strings hardcoded for the friendly names but I'd like to move these to strings.xmlto support localization.

这使用枚举toString()方法的覆盖来获取枚举值的友好名称以显示在Spinner. 目前,我的枚举具有为友好名称硬编码的字符串,但我想将它们移动strings.xml到支持本地化。

However, toString doesn't have access to a Contextso I'm not sure how to resolve the resource ids.

但是,toString 无权访问 a,Context因此我不确定如何解析资源 ID。

Is there any way of getting localised strings in the toString() method of an enum?

有没有办法在枚举的 toString() 方法中获取本地化字符串?

回答by wsanville

If I understand this correctly, the real question here is how to get a Contextfrom your enum, so that you can call Context.getString()to get localized versions of the Strings you need.

如果我理解正确,那么这里真正的问题是如何Context从您的 中获取 a enum,以便您可以调用Context.getString()以获取所需字符串的本地化版本。

One approach, would be to set a static member variable of type Contextin your application's onCreate()method, which is described in this answer. The idea here is that every time your application gets created or recreated, you'll hold on to the application context in a variable that's easy to get to.

一种方法是Context在应用程序的onCreate()方法中设置类型为静态成员变量,这在本答案中进行了描述。这里的想法是,每次创建或重新创建您的应用程序时,您都会在一个易于获取的变量中保留应用程序上下文。

Then, pass in the resource ID in the constructor of your enum values, and use the Context in your toString()method.

然后,在枚举值的构造函数中传入资源 ID,并在toString()方法中使用 Context 。

For example:

例如:

public enum Example {
    HELLO(R.string.hello),
    WORLD(R.string.world);

    private int mResourceId;

    private Example(int id) {
        mResourceId = id;
    }

    @Override
    public String toString() {
        return App.getContext().getString(mResourceId);
    }
}

回答by Coderhi

@Override public String toString() { return App.getContext().getString(id); }

@Override public String toString() { return App.getContext().getString(id); }

It's important that your enum class doesnt have any ties to your activity because if you want to use in another application then you won't be able to if your referencing a static context.

重要的是您的枚举类与您的活动没有任何联系,因为如果您想在另一个应用程序中使用,那么如果您引用静态上下文,您将无法使用。

So a better way would be to return the resource id of the string back to the activity and then let the activity grab the string using the id from their.

所以更好的方法是将字符串的资源 id 返回给活动,然后让活动使用他们的 id 获取字符串。

So from your enum class you would have a method looking something similar to this:

因此,从您的枚举类中,您将有一个类似于以下内容的方法:

    public  int getResourceId()
  {
    return resourceId;
  }

Then in your activity I would build up a list containing an arraylist:

然后在您的活动中,我将建立一个包含数组列表的列表:

final List<String> enumList = new ArrayList<String>();
for ( final MyEnum status : MyEnum.values() )
{
  enumList.add( getString( status.getResourceId() ) );
}

Then you can use enumList with your ArrayAdapter, Bingo :)

然后您可以将 enumList 与您的 ArrayAdapter、Bingo 一起使用 :)

So now you have no ties to the enum class, and so if your building another app that needs to use the same enum class you quality easily do so.

所以现在您与 enum 类没有联系,因此如果您构建另一个需要使用相同 enum 类的应用程序,您可以轻松地这样做。

回答by Oasis Feng

Use static Application is always a bad practice, because not only it breaks Instant Run, but also this is against the decoupling principle thus makes modularization difficult to implement. Not to mention Android actually supports multiple Applications in a single process.

使用静态 Application 总是不好的做法,因为它不仅破坏了 Instant Run,而且这违反了解耦原则,从而使模块化难以实现。更不用说Android在一个进程中实际上支持多个应用程序。

For this reason, I'd suggest define an inner class for the enum as your adapter entries.

出于这个原因,我建议为枚举定义一个内部类作为您的适配器条目。

enum Example {
    A(R.string.label_a),
    B(R.string.label_b);

    Example(@StringRes int label) { mLabel = label; }
    private @StringRes int mLabel;

    class Entry {
        private final Context mContext;
        Entry(final Context context) { mContext = context; }
        @Override public String toString() { return mContext.getString(mLabel); }
    }
}

Then, build an array of Example.Entry for the adapter.

然后,为适配器构建一个 Example.Entry 数组。

Arrays.stream(Example.values()).map(item -> item.new Entry(context)).toArray(Example.Entry[]::new)

回答by Gray

I'm not 100% sure I understand what you are asking.

我不是 100% 确定我明白你在问什么。

Is there any way of getting localised strings in the toString() method of an enum?

有没有办法在枚举的 toString() 方法中获取本地化字符串?

You can certainly @Overridethe toString()method inside of your myEnumto change how it is displayed:

你当然可以在你里面@OverridetoString()方法myEnum来改变它的显示方式:

public enum myEnum {
    ONE("1"),
    TWO("2");
    private String pretty;
    private myEnum(String pretty) {
        this.pretty = pretty;
    }
    @Override
    public String toString() {
        // you can localise this string somehow here
        return pretty;
    }
}