我在我的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?并把它全部放在一个循环或其他什么所以当选择后续按钮时,数字会相应加载?
答案 0 :(得分:2)
您可以创建字符串和按钮的映射。
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);
如果您将来添加额外的按钮,这也会更容易。您需要做的就是将其添加到地图中。