怎么精简这段代码
时间: 2023-08-06 22:15:52 浏览: 43
可以将重复的代码进行封装,使用一个方法来实现对某个选项的设置。同时,可以使用一个 Map 来记录每个选项对应的 ImageView 控件。具体代码如下:
```
private Map<String, ImageView> imageViewMap;
private void initSettings() {
imageViewMap = new HashMap<>();
imageViewMap.put("firstD", mBinding.carBottomLayout.ivSetUp);
imageViewMap.put("wheelangle", mBinding.carBottomLayout1.ivSetUp);
imageViewMap.put("radar", mBinding.carBottomLayout2.ivSetUp);
imageViewMap.put("turnlight", mBinding.carBottomLayout3.ivSetUp);
imageViewMap.put("lowspeed", mBinding.carBottomLayout4.ivSetUp);
for (String key : imageViewMap.keySet()) {
ImageView imageView = imageViewMap.get(key);
boolean isOpen = SpUtils.getInstance().getBoolean(key, false);
imageView.setImageResource(isOpen ? R.mipmap.sw_on : R.mipmap.sw_off);
imageView.setOnClickListener(v -> {
boolean newOpen = !isOpen;
SpUtils.getInstance().setBoolean(key, newOpen);
imageView.setImageResource(newOpen ? R.mipmap.sw_on : R.mipmap.sw_off);
});
}
}
```
这样做可以大大减少代码量,也方便后续的维护和修改。