Android Studio中如何用自定义对象ArrayList生成ListView行并动态改色
实现方案
步骤1:为Locations类补充属性Getter方法
你需要先在Locations类中新增属性的get方法,方便Adapter中读取对应属性值,代码如下:
public String getName() { return name; } public int getCurrentCapacity() { return currentCapacity; } public int getMaxCapacity() { return maxCapacity; } public int getId() { return id; }
步骤2:重写ArrayAdapter的getView方法实现自定义逻辑
默认的ArrayAdapter只能展示固定内容,你需要重写它的getView方法,同时实现名称展示和动态改色的需求,直接替换你原来的Adapter初始化代码即可:
ListView list = (ListView) findViewById(R.id.theList); // 自定义ArrayAdapter ArrayAdapter<Locations> adapter = new ArrayAdapter<Locations>(this, android.R.layout.simple_list_item_1, locationsArrayList) { @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { // 获取系统自带的列表行视图 View itemView = super.getView(position, convertView, parent); // 拿到当前行对应的Locations实例 Locations currentLocation = getItem(position); // 绑定自带的TextView控件,设置展示内容为name属性 TextView textView = itemView.findViewById(android.R.id.text1); textView.setText(currentLocation.getName()); // 按currentCapacity数值动态设置颜色,规则可自行调整 // 示例规则:当前容量占最大容量80%以上标红,50%-80%标黄,低于50%标绿 double usageRate = currentLocation.getCurrentCapacity() * 1.0 / currentLocation.getMaxCapacity(); if (usageRate >= 0.8) { itemView.setBackgroundColor(Color.RED); textView.setTextColor(Color.WHITE); } else if (usageRate >= 0.5) { itemView.setBackgroundColor(Color.YELLOW); textView.setTextColor(Color.BLACK); } else { itemView.setBackgroundColor(Color.GREEN); textView.setTextColor(Color.WHITE); } return itemView; } }; list.setAdapter(adapter);
可选补充
如果你需要更复杂的行布局,可以自己新建布局XML文件替换代码中的android.R.layout.simple_list_item_1,在getView中inflate自定义布局后读取对应控件做设置即可。
内容的提问来源于stack exchange,提问作者Zowie Tay
相关产品推荐
相关产品推荐

