我在我的android应用程序中使用以下代码:

Button selectedButton = null;
        if(mSelectedTimePeriod.equals(ChartImageData.LAST_1_DAY)){
            selectedButton = mButton1;
        }else if(mSelectedTimePeriod.equals(ChartImageData.LAST_5_DAYS)){
            selectedButton = mButton2;
        }else if(mSelectedTimePeriod.equals(ChartImageData.LAST_30_DAYS)){
            selectedButton = mButton3;
        }else if(mSelectedTimePeriod.equals(ChartImageData.LAST_3_MONTHS)){
            selectedButton = mButton4;
        }else if(mSelectedTimePeriod.equals(ChartImageData.LAST_6_MONTHS)){
            selectedButton = mButton5;
        }else if(mSelectedTimePeriod.equals(ChartImageData.LAST_1_YEAR)){
            selectedButton = mButton6;
        }else if(mSelectedTimePeriod.equals(ChartImageData.LAST_5_YEARS)){
            selectedButton = mButton7;
        }
        return selectedButton;


有什么办法可以使mbutton1类似mbutton [i]和LAST_1_DAY = LAST_ [i] _DAY吗?并将其全部放入循环或其他内容中,以便在选择后续按钮时相应加载数字?

最佳答案

您可以创建字符串和按钮的映射。

    Map<String, Button> mapping = new HashMap<String, Button>()
    mapping.put(ChartImageData.LAST_1_DAY, mbutton1);
    mapping.put(ChartImageData.LAST_5_DAYS, mbutton2);
    ....


然后您可以做。

     return mapping.get(mSelectedTimePeriod);


如果将来要添加一个额外的按钮,这也将使其变得更加容易。您需要做的就是将其添加到地图中。

09-28 13:06