GridLayout (not GridView) how to stretch all children evenly

后端 未结 20 2112
独厮守ぢ
独厮守ぢ 2020-11-22 09:35

I want to have a 2x2 grid with a buttons inside. This is only ICS so I am trying to use the new GridLayout given.

Here\'s the XML of my layout:

 <         


        
20条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 10:18

    I finally found the solution. As Rotemmiz said, you have to do it dynamically afterwards. This code stretches the buttons to fill the view horizontally, but the same can be done for vertically.

    public void fillview(android.support.v7.widget.GridLayout gl)
    {
        Button buttontemp;
    
        //Stretch buttons
        int idealChildWidth = (int) ((gl.getWidth()-20*gl.getColumnCount())/gl.getColumnCount());
        for( int i=0; i< gl.getChildCount();i++)
        {
            buttontemp = (Button) gl.getChildAt(i);
            buttontemp.setWidth(idealChildWidth);
        }
    }
    

    (The 20 is for the internal and external padding and margins. This could be done more universally, but this is far cleaner)

    Then it can be called like this:

        android.support.v7.widget.GridLayout gl = (android.support.v7.widget.GridLayout)findViewById(R.id.buttongrid);
        ViewTreeObserver vto = gl.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {@Override public void onGlobalLayout() 
        {
    
                android.support.v7.widget.GridLayout gl = (android.support.v7.widget.GridLayout) findViewById(R.id.buttongrid);
                fillview(gl);
    
                ViewTreeObserver obs = gl.getViewTreeObserver();
                obs.removeGlobalOnLayoutListener(this);
        }});
    

    It must be done with an observer because we need to wait for the view to be drawn before we call the views.

提交回复
热议问题