0

I'm trying to change the background color of my GridView. This works perfectly with this code:

GridView gv = (GridView) findViewById(R.id.gvSpeelveld);
gv.setBackgroundColor(Color.RED);

But now I want to change the color of different cells. For example: Row 2 cell 2 should be blue. What method should I use to get the GridView item on a specific position to change the color?

I tried with these methods, but it didn't work out well

//Attempt 1
gv.getChildAt(1).setBackgroundColor(Color.BLUE);
//Attempt 2 (returns data, not the whole object)
gv.getItemAtPosition(5);

So how can I the content of different cells?

Matt
  • 1,893
  • 11
  • 33
  • 57

1 Answers1

1

It is not a good practice to set the background of a particular list/grid item after execution of the adapter. The best way is to set it in the adapter itself by identifying position.e.g.

  class YourAdapter extends BaseAdapter<T>{ ....

 getView(int position, View convertView, ViewGroup parent){



 View v = convertView;
       ......



      if(position == your_postion){



                  v.setbackground(Color.parseColor("#FF0000");
            }

        }

     }
NullPointerException
  • 3,978
  • 4
  • 34
  • 52
  • And via what way can I identify the position in the adapter? – Matt Jan 24 '14 at 15:01
  • U might have used the adapter for the gridview.. so in that adapter u have the method getView(int position, View convertView, ViewGroup parent). By ths way u will get position – NullPointerException Jan 24 '14 at 15:04
  • I see, but what should I fill in with the properties? int Position is logical, View convertView seems like the GridView but what should be given with the ViewGroup parent? – Matt Jan 24 '14 at 15:07
  • I see, but I used the default ArrayAdapter class (ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,arrSpeelveld);) Is this a problem or should I define my own custom class? – Matt Jan 24 '14 at 15:17
  • 1
    No.. ArrayAdapter will not satisfy your requirement. You must have to use your custom adapter. please see the link http://stackoverflow.com/questions/6958279/how-to-use-a-custom-arrayadapter-in-a-separate-class – NullPointerException Jan 24 '14 at 15:20
  • have u tried matt? if it is worked then please accept the answer – NullPointerException Jan 24 '14 at 17:46
  • Not yet. First I'm trying to understand/make a custom adapter that works. Then I'll try to add the colors – Matt Jan 24 '14 at 19:07