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

2 回答 2

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;
}
于 2013-05-31T05:16:34.263 回答
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));
于 2013-05-31T04:10:55.963 回答