我有这种代码的和平,并希望知道如何通过循环来使它更优雅。试图将列表和适配器放在一个对象数组中,但我无法用它调用.size()
。
所以从这个:
int breakfastIndex = //get index.
if(breakfastIndex != -1 && breakfastFoodList.size() > breakfastIndex) {
breakfastFoodList.remove(breakfastIndex);
breakfastAdapter.notifyItemRemoved(breakfastIndex);
}
int lunchIndex = intent.getIntExtra("position", -1);
if(lunchIndex != -1 && lunchFoodList.size() > lunchIndex) {
lunchFoodList.remove(lunchIndex);
lunchAdapter.notifyItemRemoved(lunchIndex);
}
int dinnerIndex = intent.getIntExtra("position", -1);
if(dinnerIndex != -1 && dinnerFoodList.size() > dinnerIndex) {
dinnerFoodList.remove(dinnerIndex);
dinnerAdapter.notifyItemRemoved(dinnerIndex);
}
int snackIndex = intent.getIntExtra("position", -1);
if(snackIndex != -1 && snackFoodList.size() > snackIndex) {
snackFoodList.remove(snackIndex);
snackAdapter.notifyItemRemoved(snackIndex);
}
对此:
for(int i = 0; i < 4; i++) {
int index = //get index.
if(index != -1 && foodList[i].size() > index) {
foodList[i].remove(index);
adapter[i].notifyItemRemoved(index);
}
}
答案 0 :(得分:2)
你可以制作两个数组
List[] lists = {breakfastFoodList,...};
ArrayAdapter[] adapters = {breakfastAdapter,...};
然后,你写的那个循环看起来很好。
但是,如果您尝试一次性删除所有餐点,我觉得您应该存储一个列表,然后得到其余的
例如,
public class DailyMeal {
Meal breakfast, lunch, dinner, snack;
}
然后,为您的列表
// In the Activity
private List<DailyMeal> meals;
public List<Meal> getBreakfasts(); // return list of all breakfasts
public List<Meal> getLunches();
// etc.
当您从膳食列表中删除DailyMeal对象时,您将自动删除每个Meal对象,以及#34; day&#34;
答案 1 :(得分:1)
有些人指出我的代码包含一个错误,事后看来这似乎是我的代码看起来“难看”的原因。
我决定使用一个简单的开关。
int index = intent.getIntExtra("position", -1);
String mealType = intent.getStringExtra("mealType");
switch(mealType) {
case "BREAKFAST":
if(index != -1 && breakfastFoodList.size() > index) {
breakfastFoodList.remove(index);
breakfastAdapter.notifyItemRemoved(index);
}
break;
case "LUNCH":
if(index != -1 && lunchFoodList.size() > index) {
lunchFoodList.remove(index);
lunchAdapter.notifyItemRemoved(index);
}
break;
case "DINNER":
if(index != -1 && dinnerFoodList.size() > index) {
dinnerFoodList.remove(index);
dinnerAdapter.notifyItemRemoved(index);
}
break;
case "SNACK":
if(index != -1 && snackFoodList.size() > index) {
snackFoodList.remove(index);
snackAdapter.notifyItemRemoved(index);
}
break;
}