【问题标题】:How to use String for case label within switch statement如何在 switch 语句中使用字符串作为 case 标签
【发布时间】:2020-03-29 19:04:45
【问题描述】:

我试图弄清楚如何在这个 switch 语句中将一个字符串放入一个 case 标签中,这样它也可以在其他语言中工作。这是我目前的代码。

或者如果有更好的编码方式,那么当使用其他语言时,按钮仍然可以工作

if (profileid.equals(firebaseUser.getUid())) {
        edit_profile.setText(R.string.edit_Profile_Button);
    } else {
        checkFollow();
        saved_photos.setVisibility(View.GONE);
        my_photos.setVisibility(View.GONE);
    }
    edit_profile.setOnClickListener(v -> {
        String btn = edit_profile.getText().toString();
        switch (btn) {
            case "Edit Profile":
                startActivity(new Intent(getContext(), EditProfileActivity.class));
                break;
            case "support":
                FirebaseDatabase.getInstance().getReference().child("Support").child(firebaseUser.getUid())
                        .child("supporting").child(profileid).setValue(true);
                FirebaseDatabase.getInstance().getReference().child("Support").child(profileid)
                        .child("supporters").child(firebaseUser.getUid()).setValue(true);
                addNotifications();
                break;
            case "supporting":
                FirebaseDatabase.getInstance().getReference().child("Support").child(firebaseUser.getUid())
                        .child("supporting").child(profileid).removeValue();
                FirebaseDatabase.getInstance().getReference().child("Support").child(profileid)
                        .child("supporters").child(firebaseUser.getUid()).removeValue();
                break;
        }
    });

【问题讨论】:

    标签: java android firebase switch-statement


    【解决方案1】:

    您应该使用.properties 文件将不同语言的标签存储在一个键上,即每种语言的键将保持相同,但值将特定于语言,例如英文属性文件的名称是myapps_en.properties,德文属性文件的名称是myapps_en.properties。在这两个文件中,键将相同,但值将特定于语言。

    现在,您可以使用 case 中的键(而不是值)。

    您可以查看this,了解如何使用.properties 文件进行本地化的示例。

    【讨论】:

    • 我可以为另一种语言的文本添加另一种情况吗?当我这样做时,它似乎起作用了
    • 当然,它会起作用,但假设您有10 语言要处理,并且每种语言都有5 案例。在这种情况下,您将拥有 50 case 块。想象一下,如果采用这种实现方式,您的代码会变得多么难以管理。
    • @RyanDiskin - 我希望该解决方案对您有用。不要忘记接受答案,以便将来的访问者也可以放心地使用该解决方案。检查meta.stackexchange.com/questions/5234/… 了解如何操作。如有任何疑问/问题,请随时发表评论。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-06
    • 2017-09-06
    • 1970-01-01
    • 2014-08-05
    • 2012-01-23
    相关资源
    最近更新 更多