I have a GridView with each cell containing some text, and I want to be able to set the background colour of individual cells.
The XML for my GridView is:
The key to solving this problem is to first understand how ListView and GridView work. GridView creates and destroys child views as you scroll up and down. If you can't see an item in a GridView that means there is no child view for it, it will be created when the user actually scrolls to it. GridView uses an Adapter to create the views and GridView recycles views when they go offscreen and asks the Adapter to reuse the recycled views for new views that come on screen. The Adapter usually inflates a resource layout to create new views.
So what this means is that GridView will call getView(...) on the Adapter each time it wants to display a child view on screen, it may pass a recycled View called convertView.
The solution is to override getView(...), call super to let the Adapter create and populate the view with data from the String array normally but add a bit of code at the end before we give the view back to GridView that sets the color of the view.
new ArrayAdapter(context, android.R.layout.simple_list_item_1, student_array) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
int color = 0x00FFFFFF; // Transparent
if (someCondition) {
color = 0xFF0000FF; // Opaque Blue
}
view.setBackgroundColor(color);
return view;
}
};