简体   繁体   English

Android 通过来自 strings.xml 的值进行切换

[英]Android switch by values from strings.xml

I'm new with Android and want to understand another one moment.我是 Android 新手,想再了解一下。 I've got a strings.xml, which values I use in activity.xml.我有一个strings.xml,我在activity.xml 中使用了这些值。 How use this values from JAva code in switch block?如何在 switch 块中使用 JAva 代码中的这些值?

private void gotoActivity(CharSequence text) {
    switch (text.toString()) {
        case getString(R.string.title_activity_first):
            break;

        case RADIO_BUTTON_SECCOND:
            break;
    }
}

Not compiles 'cos of "Constant expression required".不编译“需要常量表达式”的 cos。 But the main benefit of strings.xml - is string constants in one place.但是 strings.xml 的主要好处是在一个地方使用字符串常量。

Help plz.请帮忙。

Unfortunately you cannot use resource string in switch-case.不幸的是,您不能在 switch-case 中使用资源字符串。 You have two options.你有两个选择。 Choose anyone...选择任何人...

  1. use static final String in your activity.在您的活动中使用static final String

    Example: Initialize the strings示例:初始化字符串

    public static final String TITLE_ACTIVITY_FIRST = "activity_title";

    public static final String RADIO_BUTTON_SECCOND = "radio_button_second";

    Then you can use the TITLE_ACTIVITY_FIRST in switch case.然后你可以在 switch case 中使用TITLE_ACTIVITY_FIRST like,喜欢,

     switch(text.toString()){ case TITLE_ACTIVITY_FIRST: break; case RADIO_BUTTON_SECOND: break; }

    No error will show!不会显示任何错误!

  2. use if-else.使用 if-else。 You can then use your resource strings.然后您可以使用您的资源字符串。

    Example:例子:

    if(text.toString().equals(getString(R.string.title_activity_first))){ //your code in case of 1st condition }else if(text.toString().equals(getString(R.string.title_activity_second))){ //your code in case of 2nd condition }

The second might look clumsy.第二个可能看起来很笨拙。 But you wont have to change your code too much.但是您不必过多地更改代码。 Whereas the first one might look quite handy and you can easily modify later.而第一个可能看起来很方便,以后您可以轻松修改。 Hope it helps!希望能帮助到你!

你不能使用getString(R.string.title_activity_first)因为它从应用程序包的默认字符串表中返回一个本地化的字符串。所以结果会根据语言环境而不同,因此它不会是一个常量。你甚至不能使用 getString() 方法获取特定的本地字符串。最好使用静态最终字符串代替。请参阅此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM