Android中如何根据SQLite状态值实现GridView指定项高亮
问题修复方案
- 空指针报错原因及修复
你出现Attempt to invoke virtual method 'void android.view.View.setBackgroundColor(int)' on a null object reference报错的核心原因是:getView的入参view在首次加载条目(没有可复用View)时为null,你后续操作背景时调用的是view.setBackgroundColor而非实际承载条目的row变量,所以触发空指针。
另外你代码里还存在三个隐性问题:
- 没有处理条目复用的背景重置逻辑,滑动后会出现不该高亮的条目也显示高亮的错乱问题
- ViewHolder只初始化了
txtName,但后续调用了holder.txtPrice.setText,也会触发空指针,需要统一变量名和绑定逻辑 Inventory实体类未存储status字段,inventory.getStatus()拿不到正确值
- 第一步:修改
Inventory实体类,增加status字段
public class Inventory { private String hhNumber; private int id; private int status; // 新增status字段 // 修改构造方法 public Inventory(String hhNumber, int id, int status) { this.hhNumber = hhNumber; this.id = id; this.status = status; } // 新增getStatus方法 public int getStatus() { return status; } // 原有其他getter保持不变 public String getHHnumber() { return hhNumber; } public int getId() { return id; } }
- 第二步:修改
InventoryListClass的数据库遍历逻辑,把status传入实体
try { Cursor cursor = sqLiteHelper.getData("SELECT id,hh_number,card_scanning_status FROM CgList"); list.clear(); while (cursor.moveToNext()) { int id = cursor.getInt(0); String hhNumber = cursor.getString(1); int status = cursor.getInt(2); // 构造Inventory时传入status list.add(new Inventory(hhNumber, id, status)); } adapter.notifyDataSetChanged(); } catch (Exception e){ Log.d(TAG, "Error: "+ e); }
- 第三步:修改
InventoryListAdapter的getView逻辑,修复空指针和高亮逻辑
@Override public View getView(int position, View view, ViewGroup viewGroup) { View row = view; ViewHolder holder; if(row == null){ LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); row = inflater.inflate(layout, null); holder = new ViewHolder(); // 确认你的item布局里TextView的id,和这里绑定的id保持一致 holder.txtName = (TextView) row.findViewById(R.id.txtName); row.setTag(holder); } else { holder = (ViewHolder) row.getTag(); } Inventory inventory = inventoryList.get(position); // 统一用ViewHolder里的txtName变量赋值,不要用不存在的txtPrice holder.txtName.setText("HH no: "+ inventory.getHHnumber()); int status = inventory.getStatus(); // 用row变量设置背景,不要用可能为null的view参数 if (status == 0){ row.setBackgroundColor(Color.parseColor("#FF108714")); } else { // 复用的时候重置为默认背景,避免显示错乱 row.setBackgroundColor(Color.WHITE); // 替换为你的默认背景色 } return row; } // 确认ViewHolder类的定义正确 static class ViewHolder { TextView txtName; }
内容的提问来源于stack exchange,提问作者Henry
相关产品推荐
相关产品推荐

