简明多个开关/案例陈述

时间:2013-05-31 03:47:56

标签: android loops switch-statement code-cleanup

好吧,我正试图在我的应用程序中简化一些代码。它工作正常,我只是有点强迫症,并希望不断提高性能。

以下是现在的代码:

switch(ressound){
            case R.id.button40:
            ressound = R.raw.sound40;
            soundname = (this.getString(R.string.app_name)) + " - " + (this.getString(R.string.quote40));
            break;
            }
               switch(ressound){
                case R.id.button900:
                ressound = R.raw.sound900;
                soundname = (this.getString(R.string.app_name)) + " - " + (this.getString(R.string.quote900));
                break;
                }
               switch(ressound){
            case R.id.button901:
            ressound = R.raw.sound901;
            soundname = (this.getString(R.string.app_name)) + " - " + (this.getString(R.string.quote901));
            break;
            }

这是一个音板应用程序,这是关于其中的另存为功能。有没有办法简化这些多个语句(有些屏幕有40多个声音)?使用循环看起来是一个明显的选择,但是在环顾四周之后,case语句显然必须是静态的而不是变量。

编辑:忘记包含实际的函数头:

        public boolean function1(int ressound){  

              String soundname = "";

2 个答案:

答案 0 :(得分:0)

int quoteval=0; 
switch(ressound){
            case R.id.button40:
            ressound = R.raw.sound40;
            quoteval =R.string.quote40;               
            break;
            case R.id.button900:
            ressound = R.raw.sound900;
            quoteval =R.string.quote900;
            break;
            case R.id.button901:
            ressound = R.raw.sound901;
            quoteval =R.string.quote901;
            break;

}
soundname = (this.getString(R.string.app_name)) + " - " + (this.getString(quoteval));

答案 1 :(得分:0)

有一种方法可以使用循环并消除switch-case语句。使用Resources#getIdentifier方法。假设您使用序列号(“sound_filename_1”,“sound_filename_2”等)命名资源,您可以编写如下代码:

private static ArrayList<Integer> findSoundResourceIds(Resources res) {
    ArrayList<Integer> resIds = new ArrayList<Integer>();

    int i = 1;
    do {
        int resId = res.getIdentifier("sound_filename_"+i, "raw", getPackage().getName());
        if (resId == 0) {
            break;
        }
        resIds.add(resId);
        i++;
    } while (true);

    return resIds;
}