Could you use a LinearLayout and set the layout_weight of each custom view
to 1?
Hmmm... yes, good call, but there's a slight twist. It seems that gravity
doesn't work in LinearLayout. Consider the following code (in onCreate() ):
---
super.onCreate(savedInstanceState);
// Create the root container, vertically.
LinearLayout rootContainer = new LinearLayout(this);
rootContainer.setOrientation(LinearLayout.VERTICAL);
// It fills the parent by default.
rootContainer.setBackgroundColor(Color.CYAN); // To confirm it does fill the
parent.
LinearLayout.LayoutParams constraints = null ;
// Create a horizontal container to hold a row of controls in the main
container.
LinearLayout nestedContainer = new LinearLayout(this);
nestedContainer.setOrientation(LinearLayout.HORIZONTAL);
// Add a button to this nested container.
Button goButton = new Button(this);
goButton.setText("Go!");
// Only as big as button needs to be, as little extra size as possible
please:
constraints = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, 0.0f);
nestedContainer.addView(goButton, constraints);
// Add this nested container to the parent container, aligned to the right.
nestedContainer.setGravity(Gravity.RIGHT);
// Only as big as container needs to be, as little extra size as possible
please:
constraints = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, 0.0f);
rootContainer.addView(nestedContainer, constraints);
// Assume more rows would be added to the parent...
setContentView(rootContainer);
---
If you debug that, it (the nested container with button) comes out
left-aligned instead of right. Can anyone see anything I might be doing
wrong?
This can be worked around by making the nested container FILL_PARENT, but
then LinearLayout assigns all the extra width to the controls - making the
button as wide as the physical display. The answer to that is to add empty
LinearLayouts to the start or end of the row of components to emulate
alignment. Makes a mockery of having gravity in the first place!
On the whole, though, LinearLayout is a neater solution as it doesn't rely
on resizing anything manually during a layout handler, so I'll be going with
that.
(@Mark: Your well-made point about writing my own ViewGroup didn't fall on
deaf ears - I *did* start to subclass RelativeLayout, effectively writing my
own ViewGroup with a lot of help from the system {;v) )
--
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en