Gridlayout not showing, Android studio

Ciprian Iacob picture Ciprian Iacob · Feb 27, 2016 · Viewed 7.9k times · Source

I'm trying to create an app in android studio, and for some reasons one gridLayout decides not to show up, despite the fact that it takes the necessary space on the screen. Image from android studio, actual screenshot from my phone

XML file of the layout:

Answer

Tassadar picture Tassadar · Feb 27, 2016

android:layout_columnWeight only works on api 21 or later, as per the screenshot in your device im guessing is lower.

Due to the edittext has no width specified and theres also no text defined its being showed with 0 width, thats why you seem not to see it.

I recommend defining the width and margin by code to achieve what you show on the studio screenshot:

Define a name for the gridlayout, im using in the example "gridlayout"

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    GridLayout g = (GridLayout)findViewById(R.id.gridlayout);
    int screenWidth = getScreenWidth();
    int cellWidth = screenWidth / 4;
    int margin = cellWidth / 8;
    GridLayout.LayoutParams p;
    for(int i = 0; i < g.getChildCount(); i++){
        p = (GridLayout.LayoutParams)g.getChildAt(i).getLayoutParams();
        p.width = cellWidth;
        p.setMargins(margin, margin, margin, margin);
    }
}

private int getScreenWidth(){
    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    return  size.x;
}

It will set the same look for any device and any orientation.