android gridview项目动态背景颜色

时间:2016-07-08 15:35:54

标签: java android gridview realm

我有一个带有领域对象的GridView,我可以很好地填充GridView,我无法解决的是如何根据领域对象变量更改项目的背景颜色。我需要的是如果领域对象stockEntry.VERIFIED等于1则背景颜色需要为绿色。

我确实设法通过改变view.setBackgroundColor来显示绿色,但是当我滚动更多项目时自动获得绿色背景!

public class StockEntryAdapter extends BaseAdapter {
private LayoutInflater inflater;

private List<StockEntry> stockEntries = null;

public StockEntryAdapter(Context context) {
    inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

public void setData(List<StockEntry> details) {
    this.stockEntries = details;
}

@Override
public int getCount() {
    if (stockEntries == null) {
        return 0;
    }
    return stockEntries.size();
}

@Override
public Object getItem(int position) {
    if (stockEntries == null || stockEntries.get(position) == null) {
        return null;
    }
    return stockEntries.get(position);
}

@Override
public long getItemId(int i) {
    return i;
}

@Override
public View getView(int position, View currentView, ViewGroup parent) {
    if (currentView == null) {
        currentView = inflater.inflate(R.layout.stock_entry_listitem, parent, false);
    }

    StockEntry stockEntry = stockEntries.get(position);

    if (stockEntry != null) {
        TextView textView = (TextView) currentView.findViewById(R.id.itemnmbr);
        textView.setText(stockEntry.getItemFullName());

        if (stockEntry.getVerified() == 1) {
             // here I need to set the items background colour to green
        }
    }

    return currentView;
}

2 个答案:

答案 0 :(得分:0)

试试这个

currentView.setBackgroundColor(ContextCompat.getColor(context.R.color.yellow));

答案 1 :(得分:0)

感谢@ comeback4you和@EsatIBIS,这对我有用;

public View getView(int position, View currentView, ViewGroup parent) {
    if (currentView == null) {
        currentView = inflater.inflate(R.layout.stock_entry_listitem, parent, false);
    }

    StockEntry stockEntry = stockEntries.get(position);

    if (stockEntry != null) {
        TextView textView = (TextView) currentView.findViewById(R.id.itemnmbr);
        textView.setText(stockEntry.getItemFullName());
        if (stockEntry.getVERIFIED() == 1) {
            currentView.setBackgroundColor(Color.parseColor("#A5D6A7"));
            if (stockEntry.getVARIANCECOST() > 100 || stockEntry.getVARIANCECOST() < -100) {
                currentView.setBackgroundColor(Color.parseColor("#EF9A9A"));
            }
        } else {
            currentView.setBackgroundColor(Color.WHITE);
        }
    }

    return currentView;
}