Search code examples
androidborderandroid-gridlayoutdivider

Android GridLayout Dividers


Why would Android not include the ability to border cells in a gridlayout? I have read multiple post of several ways to do this. One method I have tried with limited success is below. My problem is the horizontal line divider. When execute with the vertical and horizontal code in place, my grid ends up with cells blocked out so the text is not visible in the cell. If I remove the horizontal code, I get perfect vertical lines at each column as expected. Any idea as to what is wrong. I was able to use the same method to create gridlines on a table. The gridlayout is inside a horizontal scroll which is inside a vertical scroll. Gridlayout background is black. So I should end up with blue cells and black divider lines.

 for (int y = 0; y < rownum; y++) {
 cols = 0;
 while (cols < columnum) {
  TextView textViewD = new TextView(this);
  textViewD.setTextSize(18);
  textViewD.setWidth(300);
  textViewD.setHeight(75);
  textViewD.setTextColor(Color.WHITE);
  textViewD.setBackgroundColor(Color.BLUE);
   textViewD.setText(title);
  //CREATE VERTICAL DIVIDER LINES
            View v = new View(this);
            v.setLayoutParams(new ViewGroup.LayoutParams(3, ViewGroup.LayoutParams.MATCH_PARENT));
            v.setBackgroundColor(Color.BLACK);
    cols++;
    gridLayoutE.addView(textViewD);

    }

    //CREATE HORIZONTAL DIVIDER LINES

               View v1 = new View(this);
        v1.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, 3));
        v1.setBackgroundColor(Color.BLACK);
        gridLayoutE.addView(v1);

   }

enter image description here

Edit: This is what I found on other post about setting margins of textView

LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)textViewD.getLayoutParams(); params.setMargins(2, 2, 2, 2); textViewD.setLayoutParams(params);

I don't have a LinearLayout, when I attempt this, it crashes.


Solution

  • The other simple tricky way to get the same View like you want is:

    Because the background of your GridLayout is black already, Put your TextView inside another layout lets say LinearLayout make the layout of Textview to setparams MATCH_PARENT then apply some margins lets say 2 and then add the whole view(LinearLayout as a root). This will make the black colour to appear because margin will make the view adjust a little and therefore show some sort of boundaries just like you have shown in your image! Using this way will simplify the job and therefore you do not need to create divider lines be it horizontal nor vertical!