質問

I've read the docs, looked at some example code. I still don't understand how to use GridLayouts properly. I suspect specifically I do not understand Android Specs.

All I'd like to do at the moment is put 2 buttons in 1 row of a GridLayout. How can I do this?

Here's what I've got: first I create the Specs.
//6 rows is the goal of this View
Spec rowSpec1 = GridLayout.InvokeSpec(0, 5, GridLayout.Center);
Spec colSpec1 = GridLayout.InvokeSpec(0);
Spec colSpec1 = GridLayout.InvokeSpec(0)
Create the Buttons that are to be added:
Button bt1 = new Button(this._Context); Button bt2 = new Button(this._Context); //the this keyword is just referring to my class that extends GridLayout //Where I've stored the Activity's Context
Now Let's add the Buttons to the Grid:
this.AddView(bt1, new GridLayout.LayoutParams(rowSpec1, colSpec1)); this.AddView(bt2, new GridLayout.LayoutParams(rowSpec1, colSpec2));

The result of this is a single button in the top-left portion of my Android device. How can I insert these buttons in the desired locations programmatically? Also, I've read that Specs are really just used for alignment purposes, yet I've seen code that looks like they're being used for row and column placement for child views; which is what I'm doing. Could someone explain Android specs for me in a dumbed down fashion? Thanks guys!

役に立ちましたか?

解決

The colSpec1 variable has been defined twice, but I think that's a typo.

Assuming you mean:

Spec rowSpec1 = GridLayout.InvokeSpec(0, 5, GridLayout.Center);
Spec colSpec1 = GridLayout.InvokeSpec(0);
Spec colSpec2 = GridLayout.InvokeSpec(0);

The rowSpec1 variable starts at row 0 and span 5 rows. Both of the column specs start at column 0 and span 1 column. When the buttons are placed, the rows and columns match exactly so the buttons get stacked.

Think of a GridLayout spec as one dimension of a GridLayout cell. You need to have both dimensions of the cell to display a view within it. When placing items in a GridLayout, you have to be careful that cells don't overlap unless you want them to.

With that in mind, you may have better luck with:

Spec rowSpec1 = GridLayout.InvokeSpec(0, GridLayout.Center);
Spec rowSpec2 = GridLayout.InvokeSpec(1, GridLayout.Center);
Spec colSpec1 = GridLayout.InvokeSpec(0);
Spec colSpec2 = GridLayout.InvokeSpec(0);

Since it doesn't seem like you need to span rows, you can define the rowSpec variables with a size of 1.

Then you should be able to add the views,

this.AddView(bt1, new GridLayout.LayoutParams(rowSpec1, colSpec1));
this.AddView(bt2, new GridLayout.LayoutParams(rowSpec2, colSpec2));
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top