滚动时 Gridview 背景颜色改变颜色 Android

Gridview BackGround Color changing Color when Scrolling in Android

GridView 每次滚动时项目颜色随机变化。

每个项目的颜色都是基于 SQLite 数据库的状态,但是当我尝试多次滚动时它随机改变了项目的颜色。有什么办法可以解决这个问题吗?这是它的样子。

这是代码

GetView

private class ViewHolder{
    ImageView imageView, mPreviewCashCard;
    TextView txtName, txtPrice, txtSeriesNo;
}

@Override
public View getView(int position, View view, ViewGroup viewGroup) {
    Cursor cursor = MainActivity.sqLiteHelper.getData("SELECT id,status FROM DarkMode");
    while (cursor.moveToNext()) {
        DarkModeStatus = cursor.getString(1);
    }

    View row = view;
    ViewHolder holder = new ViewHolder();

    if(row == null){
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row = inflater.inflate(layout, null);
        holder.txtName = (TextView) row.findViewById(R.id.txtName);
        holder.txtPrice = (TextView) row.findViewById(R.id.txtPrice);
        holder.txtSeriesNo = (TextView) row.findViewById(R.id.txtSeriesNumber);
        holder.imageView = (ImageView) row.findViewById(R.id.imgFood);
        holder.mPreviewCashCard = (ImageView) row.findViewById(R.id.imgId);
        row.setTag(holder);
    }
    else {
        holder = (ViewHolder) row.getTag();
    }
    Inventory inventory = inventoryList.get(position);
    holder.txtName.setText(inventory.getName());
    holder.txtPrice.setText(inventory.getPrice());
    holder.txtSeriesNo.setText(inventory.getSeriesNumber());
    int status = inventory.getStatus();
    if (status==0 && DarkModeStatus.matches("false")){
        row.setBackgroundColor(Color.parseColor("#FEF8DD"));
    }
    else if(status==0 && DarkModeStatus.matches("true")){
        row.setBackgroundColor(Color.parseColor("#282828"));
    }

    byte[] CashCardImage = inventory.getImage();
    byte[] idImage = inventory.getIdImage();
    if(CashCardImage.length > 1)
    {
        Bitmap bitmap = BitmapFactory.decodeByteArray(CashCardImage, 0, CashCardImage.length);
        holder.imageView.setImageBitmap(bitmap);
    }
    else{
        holder.imageView.setImageResource(R.drawable.ic_image);
    }
    if(idImage.length > 1)
    {
        Bitmap bitmap2 = BitmapFactory.decodeByteArray(idImage, 0, idImage.length);
        holder.mPreviewCashCard.setImageBitmap(bitmap2);
    }
    else{
        holder.mPreviewCashCard.setImageResource(R.drawable.ic_image);
    }
    return row;
}

尝试在您的 if-else 块处理背景中添加 else 条件。

     if (status==0 && DarkModeStatus.matches("false")){
        row.setBackgroundColor(Color.parseColor("#FEF8DD"));
    }
    else if(status==0 && DarkModeStatus.matches("true")){
        row.setBackgroundColor(Color.parseColor("#282828"));
    }else {
        row.setBackgroundColor(Color.parseColor("#FFFFFF")); // white or whichever default background color you are using
    }

据我了解,这可以解决问题。