簡體   English   中英

簡化多個switch / case語句

[英]Succincting multiple switch/case statements

好吧,我正在嘗試簡化我的應用程序中的一些代碼。 它工作正常,我只是有點強迫症,想繼續改善性能。

這是有問題的代碼現在的樣子:

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 = "";
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));

有一種方法可以使用循環並消除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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM