Reputation: 7860
In my specific problem, I have a listview. In this listview I want the first row of the list always has a background color of green. I achieve that using the following code:
listView.setSelection(3);
View element = listView.getChildAt(0);
element.setBackgroundColor(Color.GREEN);
in the backdrop I am using a custom adapter to populate the listview, as the rows get recycled, the green color is redundant over new rows which appear. Following is my code for the getView method:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View first = listView.getChildAt(0);
if (convertView == null){
convertView = inflater.inflate(R.layout.list, parent, false);
}
TextView textView = ((TextView) convertView.findViewById(R.id.textView2));
textView.setText(lyrics[position]);
if(){ // Need to reference the first row here.
textView.setBackgroundColor(Color.GREEN);
}else {
textView.setBackgroundColor(Color.WHITE);
}
return convertView;
}
}
So in my case I need to know the first visible position in the listview so as I can undo the repetitive background coloring. Is there any way by which I can achieve this? I am open to changing the logic too as long as that is feasible.
Upvotes: 2
Views: 674
Reputation: 1858
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View first = listView.getChildAt(0);
if (convertView == null){
convertView = inflater.inflate(R.layout.list, parent, false);
}
TextView textView = ((TextView) convertView.findViewById(R.id.textView2));
textView.setText(lyrics[position]);
if(position==getFirstVisiblePosition()){ // Need to reference the first row here.
textView.setBackgroundColor(Color.GREEN);
}else {
textView.setBackgroundColor(Color.WHITE);
}
return convertView;
}
}
Upvotes: 1
Reputation: 14710
ListView's views are recycled, so in your adapter getView
method you should have - probably just before return convertView
:
if(position == 0) {
convertView.setBackgroundColor(Color.GREEN);
} else {
convertView.setBackgroundColor(Color.WHITE); // or whatever color
}
return convertView;
No need for below code that you have:
View element = listView.getChildAt(0);
element.setBackgroundColor(Color.GREEN);
Upvotes: 2