1
votes

I'm extending a LinearLayout to make a compound widget. The widget is set to layout_width="MATCH_PARENT".

mLabelTextView = new TextView(context);
mLabelTextView.setText("Testing");
LayoutParams labelParams = new
LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
        LayoutParams.WRAP_CONTENT, 0.0f);
labelParams.gravity = Gravity.CENTER_VERTICAL;
addView(mLabelTextView, labelParams);

mContentView = new Checkbox(content);
contentParams = new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1.0f);
contentParams.gravity = Gravity.CENTER_VERTICAL | Gravity.Right;

addView(mContentView, contentParams);

My problem is that the Gravity.Right property is taking effect on mContentView, but Gravity.CENTER_VERTICAL is. I know that mContentView is getting stretched to fill the remaining space. I've already tried just getting gravity=right by itself and that didn't work.

I have a similar code path in which I inflate a view that already has right gravity set in XML and that is working. So I must be missing something somewhere.

1

1 Answers

2
votes

If your parent LinearLayout has horizontal orientation (which you don't specify, but I'm guessing), then it will ignore all horizontal layout gravity bits. Likewise, if it has vertical orientation, then it would have ignored the CENTER_VERTICAL setting.

One trick is to wrap mContentView in a vertically oriented LinearLayout, give that wrapper a layout weight of 1 (so it fills the remaining space) and then the wrapper will honor the RIGHT gravity.

A better alternative might be to extend RelativeLayout instead of LinearLayout. That gives you 2-D control over gravity (unlike LinearLayout).