2013-05-31 140 views
0

好的,我試圖簡化我的應用程序中的一些代碼。它工作正常,我只是有點強迫症,並希望不斷提高性能。刪除多個開關/案例陳述

這裏是有問題的代碼看起來像現在:

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 = ""; 
+0

做ü這裏有任何錯誤? – Sam

+0

不,它在我的代碼中正常工作。我只是不知道如何製作,所以對於每個按鈕我都不必做出單獨的聲明 – user2328381

回答

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)); 
+0

Works(除了我必須在每個聲明中保留最後一行;我需要R.string.quote中的字符串#;不是R.raw.sound#),但我正在尋找任何可以避免必須列出每個按鈕的每個case語句的方法。得到一個單調乏味的改變所有的數字... – user2328381

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; 
}