2016-07-08 34 views
0

私は、レルムオブジェクトを持つGridViewを持っています。私はうまく行かないのは、レルムオブジェクト変数に応じてアイテムの背景色を変更する方法です。レルムオブジェクトstockEntry.VERIFIEDが1の場合、背景色が緑色である必要があります。android gridview item動的背景色

私は、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; 
} 

答えて

0

comeback4youと@EsatIBIS @の両方にこの

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

はまた、あなたもビューが背景をデフォルトにあなたのコードに 'else'ステートメントを追加ので、再利用されるので、あなたがより多くの緑取得している他の項目を制御する必要がありますオリジナル。 –

+0

彼はビューホルダークラスを使用していないので、他の部分は必要ないと思います。 – comeback4you

+0

comeback4you - 私の元のコードに非常に近い、私はcurrentView.setBackgroundColor(Color.parseColor( "#A5D6A7"))を使用しています。 @EsatIBISによって問題が強調されました。デフォルトのバックグラウンドに対してelseを持っているとは思っていませんでした。 – user260582

0

感謝をしてみてください、これは私のために働いていたものです。あなたが望むものに色を変更した後

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; 
}