搜尋

首頁  >  問答  >  主體

android - java中的switch case语句中,case所对应的数目是不确定的,能否动态改变case 的个数?

现在方法中传入的menuList的数目是不确定的,每个menuList.get(i),都对应一个runnableList.get(i)。现在需要根据menuList.size()动态改变case的数目,求思路

public boolean Confim(final Activity act, String title, final String[] menuList, final List<Runnable> runList) {
        runnableList = runList;
        AlertDialog.Builder builder = new AlertDialog.Builder(act);
        builder.setTitle(title);
        builder.setItems(menuList, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int which) {

                switch (which) {
                    case 0:
                        if (runnableList.get(0) == null) return;
                        runnableList.get(0).run();
                        break;
                    case 1:
                        if (runnableList.get(1) == null) return;
                        runnableList.get(1).run();
                        break;
                    case 2:
                        if (runnableList.get(2) == null) return;
                        runnableList.get(2).run();
                        break;
                }
            }
        });
    
        builder.show();

        return false;
    }
PHP中文网PHP中文网2809 天前479

全部回覆(2)我來回復

  • 黄舟

    黄舟2017-04-18 09:39:56

    switch case是編譯時就指定的,不能動態改變。
    另外你這個需求不能這麼實現嗎?

    ...
    if (runnableList.get(which) == null) return;
    runnableList.get(which).run();
    ...

    回覆
    0
  • 怪我咯

    怪我咯2017-04-18 09:39:56

    你這段程式碼直接把which當參數傳入就好了啊,幹嘛用switch

    回覆
    0
  • 取消回覆