Justice Bauer Justice Bauer - 1 year ago 52
Android Question

Is there a way I can simplify these statements to a just a few lines of code?

I am using the following code in my android app :

Button selectedButton = null;
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;

Is there a way I can make the mbutton1 something like mbutton[i] and LAST_1_DAY = LAST_[i]_DAY ? and put it all in a loop or something so when a subsequent button is selected, the number loads up accordingly?

Answer Source

You could create a mapping of String and Buttons.

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

And then you can do.

     return mapping.get(mSelectedTimePeriod);

This also makes it easier if you were to add an extra button in the future. All you need to do is add it to the map.