Change Color of cell of grid - android

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.

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.

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

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

Related

How to set ImageView Looping while i only have limited images ? (Android)

I have array drawable, the array drawable only have 4 images, and i have could be more than 4 ImageView, How to set image on the ImageView by looping, and when the looping reach more than 4, i want it's return to the first image, so it will be like this:
ImageView 1 with first drawable
ImageView 2 with second drawable
ImageView 3 with third drawable
ImageView 4 with fourth drawable
ImageView 5 with first drawable
ImageView 6 with second drawable
and so on..
How to do that ?
Any help will be appreciate, thank you!
u can use % operator. It returns remainder of a division.
For example, if you have 6 views and 4 images, you can do this way:
ImageView[] viewsArray = new ImageView[6];
//init your array with findViewById()
for(int i = 0; i < viewsArray.length; ++i) {
viewsArray[i].setImageDrawable(imagesArray[i % 4]); // if your index is 5 % operator will return 1.
}

Android LinearLayout how to access a cell in a matrix

I am developing a Tic-Tac-Toe game in which the size is N*N and not 3*3, and I am using ImageView to implement the game board.
As a beginning I am trying to implement the board as a matrix in which I will be able to access any cell because I am adding a single player mode with an AI.
The code that builds the board on the screen in the onCreate method is this:
//defining the board and parameters
main = new LinearLayout(this);
main.setOrientation(LinearLayout.VERTICAL);
LayoutParams params = new LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
main.setLayoutParams(params);
//implementing the board
for (int j = 0; j < k; j++) {
row = new LinearLayout(this);
row.setOrientation(LinearLayout.HORIZONTAL);
row.setLayoutParams(params);
for (int i = 0; i < k; i++) {
//drawing empty spaces in the squares, player=1 is for the player and player=2 is for the AI
player=0;
MyImageView cell = new MyImageView(this,player); //code that draws on the board using MyImageView - a class that extends ImageView
Board[j][i]=player;
cell.setLayoutParams(new LayoutParams(width / k, width / k));
cell.setOnClickListener(this);
row.addView(cell);
}
main.addView(row);
}
setContentView(main);
k is the order of the board matrix.
Now, my problem is that I don't know how to access to a certain cell through the MainActivity class and draw a Circle in it, because the player is the X and the AI is the Circle.
I only need help in implementing the board so that I will be able to access any cell on it.
You need a coordinate-system and a way to identify the different cells. For instance each cell could get an id like this
cell.setId(numCells++);
where numCells is set to 0 before the first for-loop.
An other way is maybe to create a grid and store the coordinate in the tag of the cell:
cell.setTag(tag)
where tag is
tag = String.valueOf(j)+"x"+String.valueOf(i)
Or you could store the formentioned ids of the cells in a array-grid and access the right cell based on the position in the grid.
EDIT:
You can access a specific sell by calling :
cellToDrawIn = findViewById(AI-prefered cell ID);
or
cellToDrawIn = findViewByTag(AI-prefered cell TAG);
How the get the ids or tags depend on how your AI calculates where it whant to put a circle.
Remeber, this a one of many possible solutions...
And are GridView out of the question?

Creating a GridView-like layout in Android without using GridView

So I'm trying to create a GridView style layout in Android without actually using a custom Gridview adapter, since I don't want it to scroll. I've tried just turning scrolling off, but it ruins my layout since I'm adding other elements around it in a vertical LinearLayout.
My next experiment was to use a TableLayout and then just add inflated layouts as table cells, but I'm also having an issue with this. Here is a test that I am running for a brief proof of concept:
TableRow trackingActivityRow = new TableRow(getActivity());
for(int j = 0; j < trackingActivities.size(); j ++) {
TrackingActivity trackingActivity = trackingActivities.get(j);
View trackingActivityCell = getActivity().getLayoutInflater()
.inflate(R.layout.table_cell_tracking_activity, trackingActivityRow, true);
TextView txtDescription = (TextView)trackingActivityCell.findViewById(R.id.txtDescription);
txtDescription.setText(trackingActivity.getDescription());
}
tableLayout.addView(trackingActivityRow);
It seems to create the number of cells correctly, but it doesn't want to set the text like it should be. Furthermore, I'm having an issue of logic when it comes to creating a new row for every 4 TrackingActivities.
If anyone has any input it would be appreciated.
/Update/
Here is a graphic of the issue. The cell with "Walk" in it is displaying correctly, but the other cells only display the placeholder text inside the textview which should have been replaced.
I created a customized GridView based on a tablelayout with a listadapter.
Simplified version of the setAdapterMethod in the extended TableLayout:
int itemPos = -1;
int numRows = (int) Math.ceil((double) adapter.getCount() / (double) mNumColumns);
for (int yPos = 0; yPos < numRows; yPos++) {
//Create new row
TableRow tableRow = new TableRow(this.getContext());
for (int xPos = 0; xPos < mNumColumns; xPos++) {
itemPos++;
View itemView = adapter.getView(itemPos, null, tableRow);
tableRow.addView(itemView);
}
this.addView(tableRow, new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.MATCH_PARENT));
}

Trying to set background color of a cell(row/col) in GridView Android

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.
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/

Change ListView divider length based on longest Text in List

I've been looking at things on Stackoverflow and cannot find out how to do this.
What I want is something like this:
xxxxxxxx
--------
xxxx
--------
xx
Instead of the usual
xxxxxxxx
----------------------------------- (until end of screen)
xxxx
-----------------------------------
xx
I wonder if there is an really easy way to do it.
I figure it involves changing the right margin but that's about as far as I got.
I am creating my ListViews at run-time by the way.
You should do something like this with a custom drawable :
<ListView
android:divider="#drawable/fancy_gradient"
android:dividerHeight="#dimen/divider_height"...
Java way :
list = (ListView) findViewById(R.id.list);
int[] colors = {0, 0xFF97CF4D, 0};
ListView inner = list.getRefreshableView();
inner.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));
inner.setDividerHeight(1);
But it seems that divider width is not customizable...
Since you can't directly change divider width programmatically, I suggest writing an adapter which takes your string list. Adapter will be consisting of one TextView and one ImageView(preferably).
In the adapter you can compare strings and get the longest one. Get estimated width for that longest string by;
String longestText = "longestword";
Paint paint = new Paint();
float widthValue = paint.measureText(longestText);
(that will give you the result in pixels) And after getting this value, you can simply put an imageview of (height=x , width=widthValue) under the textview.
Then remove the divider from your listview in xml by;
android:divider="#android:color/transparent"
and your view as you desire is ready to use.
Got it to work I think. It seems to work.
Here is how I did it.
ListAdapter listAdapter = posList.getAdapter();
//base case
int longestWidth = listAdapter.getView(0, null, posList).getMeasuredWidth();
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, posList);
listItem.measure(0, 0);
//check if the items in the list are longer than base case
if (listItem.getMeasuredWidth() > longestWidth)
{
longestWidth = listItem.getMeasuredWidth();
}
}
ViewGroup.LayoutParams params = posList.getLayoutParams();
//assign width of textview to longest item in the list
params.width = longestWidth;

Categories

Resources