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:
<GridView android:id="@+id/students_grid"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="6"
android:gravity="center"
android:stretchMode="columnWidth">
</GridView>
The code for my GridView is:
GridView gridView = (GridView) findViewById(R.id.students_grid);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, student_array);
gridView.setAdapter(adapter);
I had hoped I would be able to set the background colour of individual cells using:
gridView.getChildAt(random_student).setBackgroundColor(Color.parseColor("#18A608"));
However, this throws a null pointer exception, and on further examination it seems that gridview.getChildCount() returns 0. I have seen that gridview.getCount returns the number of items in the gridview correctly, but this doesn't help me to set the background colour of individual cells.
Any ideas where I go next?
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<String>(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;
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With