arleitiss
arleitiss

Reputation: 107

Android ListView - change background of element based on values

I have a list which lists EXPENSES and INCOMES. I want ListViewer to automatically change background to either green for Incomes or red for Expenses, would this be possible?

final DbCon database = new DbCon(this);
        final ListView Viewer = (ListView)findViewById(R.id.historyViewer);
        //date1, time1, desc1, val1, cat1, type1
        final SimpleAdapter La = new SimpleAdapter(this, database.GetMonths(), R.layout.mviewer, new String[] {"month"}, new int[] {R.id.month_name});
        Viewer.setAdapter(La);

Upvotes: 0

Views: 1190

Answers (2)

LuxuryMode
LuxuryMode

Reputation: 33771

Yes just put the logic in the getView method of your Adapter, e.g.:

public View getView(int position, View convertView, ViewGroup parent) {
   View myView;

   if(convertView == null) {
       myView = new MyView();
} else {
     myView = (MyView) convertView;
}

if(myList.get(position).isExpense) {
    myView.setBackgroundColor(Color.RED);
} else {
   myView.setBackgroundColor(Color.GREEN);
}
   return myView;       

}

edit:

Yes, I see that you are using a SimpleAdapter. That will not be sufficient to do what you want. You need to create your own adapter by subclassing BaseAdapter (or something similar) and overriding the necessary methods, e.g. getView as I showed above.

Upvotes: 0

codeMagic
codeMagic

Reputation: 44571

Without seeing any code, its hard to give any "real" help but it is possible. You can change the background color with something like

rowView.setBackgroundColor(Color.GREEN);

assuming rowView is your current View in the List. You can also change styles and themes depending on what you want.

Upvotes: 1

Related Questions