Change Color of cell of grid

老子叫甜甜 提交于 2019-12-18 09:16:21

问题


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.


回答1:


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.




回答2:


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




回答3:


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;
    }
}


来源:https://stackoverflow.com/questions/12315714/change-color-of-cell-of-grid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!