如何简化不使用if语句的方法

时间:2014-10-08 15:13:18

标签: android if-statement

如何简化不使用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张图片时,代码有点大。有谁知道解决方案?谢谢

1 个答案:

答案 0 :(得分: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--;
}