有没有办法让下面的脚本更有效率? 我想让这段代码易于维护,这就是为什么我想摆脱 if else if 的原因。 我希望你们能在这里帮助我。在底部是我想看到的东西,当然如果可能的话。
if (category.equals("infusion")){
layout.setBackgroundResource(R.color.infusion);
title.setText(R.string.title_infusion);
} else if (category.equals("pills")){
layout.setBackgroundResource(R.color.pills);
title.setText(R.string.title_pills);
} else if (category.equals("pumps")){
layout.setBackgroundResource(R.color.pumps);
title.setText(R.string.title_pumps);
} else if (category.equals("oxygen")){
layout.setBackgroundResource(R.color.oxygen);
title.setText(R.string.title_oxygen);
} else if (category.equals("scores")){
layout.setBackgroundResource(R.color.scores);
title.setText(R.string.title_scores);
} else if (category.equals("converters")){
layout.setBackgroundResource(R.color.converters);
title.setText(R.string.title_converters);
}
是这样的吗?
layout.setBackgroundResource(R.color.*category*);
title.setText(R.string.title_*category*);
最佳答案
我很确定您要“简化”的所有事情都会涉及反射,并且最终可能会使您的代码变慢且更难理解。您所拥有的是进行此设置的完全有效的方法,对读者来说非常清楚,并且不涉及任何奇怪的技术。
即这行得通,为什么要修复它?
好的,编辑:
在启动时,您可以通过 HashMap 将您的字符串值映射到资源 ID。
类似于:
HashMap map = new HashMap();
map.put("infusion",R.id.infusion);
然后是:
layout.setBackgroundResource(map.get(category));
title.setText(category);
这可能有效,但在我看来这并不是真正的改进。
关于java - 为 R.color ."string"使用字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20668563/