Reputation: 6508
I'm trying to change the background color of a specific row in a ListView to match a specific color in my List<String> hexcodeList
, which contains colors hex codes. However, I'm not using a CustomAdapter for this, instead I'm overriding getView
from ArrayAdapter
. I want the 1st row to have the 1st color of my list, the 2nd to have the 2nd color and so on. I'm very new to Java, my first thought was to use a for statement, so the code below is what I tried with no success, since this changes the background color of all rows using the last color of hexcodeList
.
ListView CoresListView = (ListView) findViewById(R.id.ListViewId);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, hexcodeList){
@Override
public View getView(int position, View convertView, ViewGroup parent){
View view = super.getView(position,convertView,parent);
for (position = 0; position < hexcodeList.size(); position++) {
view.setBackgroundColor(Color.parseColor(hexcodeList.get(position)));
}
return view;
}
};
CoresListView.setAdapter(adapter);
Upvotes: 2
Views: 1102
Reputation: 21736
You don't need for loop because the getView()
always called for each row item view.
Try this:
ListView CoresListView = (ListView) findViewById(R.id.ListViewId);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, hexcodeList){
@Override
public View getView(int position, View convertView, ViewGroup parent){
View view = super.getView(position,convertView,parent);
view.setBackgroundColor(Color.parseColor(hexcodeList.get(position)));
return view;
}
};
CoresListView.setAdapter(adapter);
Upvotes: 2
Reputation: 625
On each view created you are looping through the list and setting all colors so the last color is being set for each view.
Remove the loop and just write this:
view.setBackgroundColor(Color.parseColor(hexcodeList.get(position)));
getView(...) is called for each view so need of a loop.
Upvotes: 2