我目前正在为巴士建立一个像Bar一样的自定义进度。该程序需要显示公交车从一个位置到另一个位置的进度。
目前进度条正在制定时间表。并且代码采用switch语句的形式,但是switch语句对于编程来说变得非常冗长乏味,我仍然需要做更多的事情。
有没有办法缩短这段代码?也许是一种循环形式
Thread t = new Thread(){
@Override
public void run() {
while (!isInterrupted()) {
try {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
@Override
public void run() {
Calendar c = Calendar.getInstance();
mHours = c.get(Calendar.HOUR_OF_DAY);
mMinutes = c.get(Calendar.MINUTE);
mSeconds = c.get(Calendar.SECOND);
String mTimeString = ""+mHours + mMinutes;
ImageView busBar = (ImageView) findViewById(R.id.bus_bar);
int intTimeString = Integer.valueOf(mTimeString);
switch(intTimeString)
{
case 1030:
case 1040:
case 1052:
case 1103:
case 1115:
case 1130:
case 1140:
case 1152:
case 1203:
busBar.setImageResource(R.drawable.bus_bar);
break;
case 1031:
case 1042:
case 1054:
case 1105:
case 1131:
case 1141:
case 1154:
case 1205:
busBar.setImageResource(R.drawable.bus_bar_02);
break;
case 1032:
case 1044:
case 1055:
case 1107:
case 1132:
case 1143:
case 1155:
case 1207:
busBar.setImageResource(R.drawable.bus_bar_03);
break;
case 1033:
case 1046:
case 1057:
case 1109:
case 1133:
case 1145:
case 1157:
case 1209:
busBar.setImageResource(R.drawable.bus_bar_04);
break;
case 1034:
case 1048:
case 1059:
case 1110:
case 1116:
case 1134:
case 1147:
case 1159:
case 1210:
busBar.setImageResource(R.drawable.bus_bar_05);
break;
case 1035:
case 1049:
case 1100:
case 1112:
case 1135:
case 1149:
case 1200:
case 1212:
busBar.setImageResource(R.drawable.bus_bar_06);
break;
case 1036:
case 1050:
case 1101:
case 1113:
case 1136:
case 1150:
case 1201:
case 1213:
busBar.setImageResource(R.drawable.bus_bar_07);
break;
case 1039:
case 1051:
case 1102:
case 1114:
case 1117:
case 1139:
case 1151:
case 1202:
case 1214:
busBar.setImageResource((R.drawable.bus_bar_08));
break;
}
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
t.start();
您可以尝试将一个案例的所有时间收集到一个数组或列表中,然后使用if / else来检查每个案例。
使用“contains”在Java中有一些简单的选项(请点击此处:One liner to check if element is in the list)
例如:
List<Integer> case1List = Arrays.asList(new Integer[] {1030, 1040, 1052, 1103, 1115, 1130, 1140, 1152, 1203});
List<Integer> case2List ....
....
if (case1List.contains(intTimeString)) {
//do something
}
else if (case2List.contains(intTimeString) {
//do something
}
....
有几种方法可以做到这一点:您可以将图像存储在可迭代的集合中。使用地图尝试它可能会很有趣:
Map<Int, Object> busImageMap = new HashMap<>();
例如。然后将你的时间int映射到你想要的图像:
busImageMap.put(1203, R.drawable.bus_bar);
... etc.
然后检查你的intTimeString是否在地图中:
if (busImageMap.containsKey(intTimeString)){
busBar.setImageResource(busImageMap.get(intTimeString));
}
你仍然需要将你的时间点映射到你想要的图像,但这至少给你一个更整洁的迭代器。