Reputation: 111
I am trying to write my own layout class which places it children in a regular grid. The layout itself works nicely, but I can't get the text on the buttons inside this layout to be centered. When I place the same buttons in a LinearLayout the button text is centered as desired, so the fault is probably within my layout. But how can my layout affect the gravity of the text on its child views? I suspect it has something to do with the layout parameters but I don't really know how this works yet.
Here are some code snippets which might be relevant to the problem:
My layout class WeightedGridLayout:
public class WeightedGridLayout extends ViewGroup {
// ...
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
for (int i = 0, N = getChildCount(); i < N; i++) {
View c = getChildAt(i);
// ...
// do some calculation
//
c.layout( childLeft, childTop, childRight, childBottom );
}
}
public static class LayoutParams extends ViewGroup.MarginLayoutParams {
public Position position = position( 0, 0 );
public Span span = span( 1, 1 );
// Position and Span are local classes which are irrelevant here
public LayoutParams( Position position, Span span ) {
super(FILL_PARENT, FILL_PARENT);
this.position = position;
this.span = span;
}
public LayoutParams( Position position ) {
this( position, span(1,1) );
}
public LayoutParams() {
this( position(0,0), span(1,1) );
}
public LayoutParams(MarginLayoutParams params) {
super(params);
}
public LayoutParams(LayoutParams that) {
super(that);
this.position = that.position;
this.span = that.span;
}
public LayoutParams(Context context, AttributeSet attrs) {
super(context, attrs);
}
}
The class is used like this:
WeightedGridLayout grid = (WeightedGridLayout) findViewById(R.id.mainMenu);
LayoutInflater inflater = getLayoutInflater();
Button button = (Button)inflater.inflate(R.layout.buttonproperties, null);
button.setText( "None" );
WeightedGridLayout.Position pos = WeightedGridLayout.position(colIdx,rowIdx);
WeightedGridLayout.LayoutParams lp = new WeightedGridLayout.LayoutParams(pos);
lp.setMargins(5,20,5,20);
grid.addView(button, lp );
Here are the properties for the button:
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:background="@drawable/default_button"
android:gravity="center"
android:textSize="@dimen/text"
android:textColor="@color/text" >
</Button>
The button text appears at the top of the button rather than in the center as it should. What do I have to do in order to get the text to the center?
Upvotes: 4
Views: 2344
Reputation: 111
OK, I found the problem: I failed to override onMeasure(). The layout of child views will only work if onMeasure() calls the function measure() at some point. Here is a good working example http://www.arpitonline.com/blog/2012/07/01/creating-custom-layouts-for-android/. I just wish the official documentation for custom layouts would mention this point.
Upvotes: 3