3

how do i set a custom color for a row/col in gridview in android?

My gridView consists of a gridArray of type Items which I pass all the data I want it to display, its for a timetable. I calculate the position of the items based on where I want them and then Display the items. I am not able to change the background color of the cell. How would I go about doing that.

for (int d1 = 0; d1 < days.size(); d1++) {
            if (myModules.get(1).equals(days.get(d1))) {
                for (int e1 = 0; e1 < times.size(); e1++) {
                    if (startEndM1[0].equals(times.get(e1))) {
                        gridArray.set(((e1 * 5) + d1),new Item(myModules.get(0)));
                        if (!startEndM1[1].equals(times.get(e1 + 1))) {
                            gridArray.set((((e1 * 5) + d1) + 5), new Item(myModules.get(0)));                           
                        }
                        int position = ((e1 * 5) + d1);
                        ((View) gridView.getItemAtPosition(position)).setBackgroundColor(Color.BLUE);
                    }
                }
            }
        }

the above code is justto set an item onto its specified position, If I have to change the color of that particular backgorund cell where I am setting the item, it crashes. The Grid view should recognize the position of the item where its at. Some help would be really apprectiated, thanks.

sponturious
  • 131
  • 1
  • 9

1 Answers1

3

ok first of all, i made a crossword game and also had to change background color of cell ... i made it this way

View tv = (View) gridView.getChildAt(i);
tv.setBackgroundColor(Color.RED);

also anothers links that helped me a lot were :

Change Color of cell of grid

http://eureka.ykyuen.info/2010/03/15/android-%E2%80%93-applying-alternate-row-color-in-listview-with-simpleadapter/

Community
  • 1
  • 1
Matej Špilár
  • 2,617
  • 3
  • 15
  • 28
  • It gives me a null pointer exception if I try to do that, I don't get it, It doesn't seem to find anything at that position or any position for that matter. – sponturious Mar 31 '14 at 16:58
  • That is not possible because isn't the size of the gridView supposed to be set accordingly when i define the customadapter `customGridAdapter = new CustomGridViewAdapter(this, R.layout.row_grid, gridArray);` so it should automatically get the gridArray size.? no? – sponturious Mar 31 '14 at 17:07
  • yes it is ... but make sure and you logcat to make sure that "i" is below gridArray size ... also try to change color in getView method of your custom adapter ... – Matej Špilár Mar 31 '14 at 17:10
  • 1
    Its fine thanks, I figured out another way of doing it, Cheers. I made a separate data Structure to facilitate my problem. – sponturious Mar 31 '14 at 17:19
  • Could you please post the solution you found? – KinGPinG Nov 13 '14 at 22:50
  • sponturious, please let us know what u found. we badly need it. – Syed Md. Kamruzzaman Dec 15 '15 at 13:19