简体   繁体   中英

Set layout_column and layout_row in GridLayout programmatically

I have a GridLayout (not GridView) where I want to add some views with a special row and column inex. In XML I can set the View with:

<TextView
    android:id="@+id/textView1"
    android:layout_column="2"
    android:layout_row="4"
    android:text="Large Text" />

But how can I set the attributes layout_column and layout_row programmatically? I want something like this:

GridLayout grid = new GridLayout(getActivity());

grid.setColumn(2);
grid.setRow(4);

grid.addView(new Button(getActivity());

The equivalent of layout_column and layout_row , as with all layout_... parameters, is to be found as a parameter of a subclass of LayoutParams .

In this case it's GridLayout.LayoutParams , and we use it like this (for a 2x2 grid with a subview in the final row and column, centred within the cell):

gridLayout.setColumnCount(2);
gridLayout.setRowCount(2);

gridLayout.addView(subview, new GridLayout.LayoutParams(
                              GridLayout.spec(1, GridLayout.CENTER),
                              GridLayout.spec(1, GridLayout.CENTER)));

You have to do something like this:

GridLayout gridLayout = new GridLayout(this);
gridLayout.setColumnCount(2);
gridLayout.setRowCount(4);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM