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
andGridView
work.GridView
creates and destroys child views as you scroll up and down. If you can't see an item in aGridView
that means there is no child view for it, it will be created when the user actually scrolls to it.GridView
uses anAdapter
to create the views andGridView
recycles views when they go offscreen and asks the Adapter to reuse the recycled views for new views that come on screen. TheAdapter
usually inflates a resource layout to create new views.So what this means is that
GridView
will callgetView(...)
on theAdapter
each time it wants to display a child view on screen, it may pass a recycled View calledconvertView
.The solution is to override
getView(...)
, call super to let theAdapter
create and populate the view with data from theString
array normally but add a bit of code at the end before we give the view back toGridView
that sets the color of the view.Main activity where you have to create array of hexadecimal color code and and pass to custom adapter class
In custom adapter code will be like this where color code will be parsed
You need to create a custom layout and use it in your adapter instead of
android.R.layout.simple_list_item_1
. For example:(I simply copied the latest version of
simple_list_item_1.xml
and added the new background color at the end.)Save this as
grid_layout.xml
inres/layout
and change your adapter's constructor to: