Change Color of cell of grid

2020-02-15 04:17发布

I want to change the color of the grid cell using the number of grid position . e.g. I have 5X6 grid means 30 gridItems so i want to change the color of 21st position. Please tell me how can i do this Without clicking on the Grid View.

3条回答
神经病院院长
2楼-- · 2020-02-15 04:37

In order to set color in grid cell while inflating grid cell's layout, in your baseadapter class create a cell's array then set the color as you wish.

Like

LayoutInflater li = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        grd = li.inflate(R.layout.grid_item, null);
FrameLayout dgcl = (FrameLayout) grd.findViewById(R.id.grditm);
        parent_l[position] = dgcl;

then

parent_l[21].setBackgroundColor(Color.RED);

here griditm is the id of the layout grid_item

查看更多
你好瞎i
3楼-- · 2020-02-15 04:39

First you must decide the order of the grid, where are columns, and where are lines. For example:

1 2 3 4 5

6 7 8 9 10

etc..

then just do a multiplication

i = Y*numberOfColums  + X;
grid[i].myColor = Color(R,G,B);

I'm assuming 0 based index, that simply means: if there are 6 columns:

0 <= X <= 5

if there are 5 rows

0 <= Y <=4

0 based index allows you to iterate the whole grid in a very simple manner

for(int x = 0; x < numberOfColumns; x++)
{
    for(int y = 0; y < numberOfRows; y++)
    {
        i = Y*numberOfColums  + X;
    }
}
查看更多
时光不老,我们不散
4楼-- · 2020-02-15 04:50

You will need to define a custom adapter for this.
In the getView() method of adapter you'll have to check the position parameter if is equal with 21. If it's equal with 21, then change the background for currently cell.

If you did not had the experience to define a custom adapter yet, then it will make more sense to pass through an example first.
Here's an example of a GridView that uses a custom adapter to display images.

查看更多
登录 后发表回答