GridLayout (not GridView) how to stretch all children evenly

后端 未结 20 2214
独厮守ぢ
独厮守ぢ 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:29

    In my case I was adding the buttons dynamically so my solution required some XML part and some Java part. I had to find and mix solutions from a few different places and thought I will share it here so someone else looking for the similar solution might find it helpful.

    First part of my layout file XML...

    
    
    

    grid:useDefaultMargins="true" is not required but I added because that looked better to me, you may apply other visual affects (e.g. padding) as mentioned in some answers here. Now for the buttons as I have to add them dynamically. Here is the Java part of my code to make these buttons, I am including only those lines related to this context. Assume I have to make buttons from as many myOptions are available to my code and I am not copying the OnClickListener code as well.

    import android.support.v7.widget.GridLayout;   //Reference to Library
    
    public class myFragment extends Fragment{
        GridLayout gl_Options;
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            gl_AmountOptions = (GridLayout)view.findViewById( R.id.gl_AmountOptions );
            ...
            gl_Options.removeAllViews();     // Remove all existing views
            gl_AmountOptions.setColumnCount( myOptions.length <= 9 ? 3: 4 );  // Set appropriate number of columns
    
            for( String opt : myOptions ) {
                GridLayout.LayoutParams lParams   = new GridLayout.LayoutParams( GridLayout.spec( GridLayout.UNDEFINED, 1f), GridLayout.spec( GridLayout.UNDEFINED, 1f));
                // The above defines LayoutParameters as not specified Column and Row with grid:layout_columnWeight="1" and grid:layout_rowWeight="1"
                lParams.width = 0;    // Setting width to "0dp" so weight is applied instead
    
                Button b = new Button(this.getContext());
                b.setText( opt );
                b.setLayoutParams(lParams);
                b.setOnClickListener( myClickListener );
                gl_Options.addView( b );
            }
        }
    }
    

    As we are using GridLayout from support library and not the standard GridLayout, we have to tell grade about that in YourProject.grade file.

    dependencies {
        compile 'com.android.support:appcompat-v7:23.4.0'
        ...
        compile 'com.android.support:gridlayout-v7:23.4.0'
    }
    

提交回复
热议问题