2014-10-08 17 views
0

如何簡化不使用if語句,並減少我的代碼行數的方法。下面是我的寫法:如何簡化不使用該方法的if語句

private void RemoveImg() { 
     while (true) { 
      rel_with_images.getChildCount(); 

      if ((number_of_Image== 5) { 
       rel_with_images.removeViewAt(number_of_Image- 1); 
       sp_1 = sp11.play(sp_1 , 1.0F, 1.0F, 0, 0, 1.0F); 
       inta11 = sp11.play(intaa, 1.0F, 1.0F, 0, 0, 1.0F); 
       CheckVibrate(); 
       MainAct c5 = MainAct .this; 
       c5.number_of_Image = (-1 + c5.number_of_Image); 
       break; 
      } 
      if ((number_of_Image== 4) { 
       rel_with_images.removeViewAt(number_of_Image- 1); 
       sp_1 = sp11.play(sp_1 , 1.0F, 1.0F, 0, 0, 1.0F); 
       inta11 = sp11.play(intaa, 1.0F, 1.0F, 0, 0, 1.0F); 
       CheckVibrate(); 
       MainAct c5 = MainAct .this; 
       c5.number_of_Image = (-1 + c5.number_of_Image); 
       break; 
      } 
      if ((number_of_Image== 3) { 
       rel_with_images.removeViewAt(number_of_Image- 1); 
       sp_1 = sp11.play(sp_1 , 1.0F, 1.0F, 0, 0, 1.0F); 
       inta11 = sp11.play(intaa, 1.0F, 1.0F, 0, 0, 1.0F); 
       CheckVibrate(); 
       MainAct c5 = MainAct .this; 
       c5.number_of_Image = (-1 + c5.number_of_Image); 
       break; 
      } 
      if ((number_of_Image== 2) { 
       rel_with_images.removeViewAt(number_of_Image- 1); 
       sp_1 = sp11.play(sp_1 , 1.0F, 1.0F, 0, 0, 1.0F); 
       inta11 = sp11.play(intaa, 1.0F, 1.0F, 0, 0, 1.0F); 
       CheckVibrate(); 
       MainAct c5 = MainAct .this; 
       c5.number_of_Image = (-1 + c5.number_of_Image); 
       break; 
      } 
      if ((number_of_Image== 1) { 
       rel_with_images.removeViewAt(number_of_Image- 1); 
       sp_1 = sp11.play(sp_1 , 1.0F, 1.0F, 0, 0, 1.0F); 
       inta11 = sp11.play(intaa, 1.0F, 1.0F, 0, 0, 1.0F); 
       CheckVibrate(); 
       MainAct c5 = MainAct .this; 
       c5.number_of_Image = (-1 + c5.number_of_Image); 
       break; 
      } 
     } 
} 

number_of_Image是Integer,它用相對佈局rel_with_images來計數圖像的數量。當佈局中有超過30張圖片時,代碼有點大。有誰知道解決方案?由於

+4

爲什麼你的if語句開始嗎?據我所知,每個if語句中的代碼都是相同的。毫無意義的陳述(除非我讀錯了),只要刪除它。 – apmartin1991 2014-10-08 15:57:44

回答

2
private void removeAllImages() { 
    int numberOfImages = rel_with_images.getChildCount(); 

    while (numberOfImages > 0) { 
     removeImageAt(number_of_Image-1) 
     numberOfImages = rel_with_images.getChildCount(); 
    } 
} 

private void removeImageAt(int position) { 
    rel_with_images.removeViewAt(position); 
    sp_1 = sp11.play(sp_1 , 1.0F, 1.0F, 0, 0, 1.0F); 
    inta11 = sp11.play(intaa, 1.0F, 1.0F, 0, 0, 1.0F); 
    CheckVibrate(); 
    MainAct c5 = MainAct .this; 
    c5.number_of_Image--; 
} 
+0

請注意,我對removeImageAt(int)'的內容會工作/編譯沒有多大信心 - 它只是對原始問題中的內容進行重構。 – ataulm 2014-10-08 15:30:22

+0

謝謝你的迴應。你的代碼工作我只是測試它,但從佈局中刪除所有視圖。 RemoveImg方法每個用戶點擊一次只刪除一個圖像。 – ArmsOP 2014-10-08 15:38:57

+0

我修復了它現在的工作。我把打破而(numberOfImages> 0){ removeImageAt(number_of_Image-1) numberOfImages = rel_with_images.getChildCount(); 休息; } 謝謝 – ArmsOP 2014-10-08 16:21:25