Textview gravity in custom ViewGroup

2.6k views Asked by At

I have a custom view that extends ViewGroup and I don't know why but I can't center the text of my TextView vertically.

This is how I do it:

TextView myTextView = new TextView(mContext);
myTextView.setBackgroundColor(0xFFFF9900);
myTextView.layout(left, top, right, bottom);
myTextView.setGravity(Gravity.CENTER); // with this, the text is centered horizontally but is still on top. There is plenty of space below
this.addView(myTextView);

I have do this a lot of time on LinearLayout or RelativeLayout, I should have missed something but what?

Edit:

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {

Point centerOfView = new Point(this.getMeasuredWidth()/2, this.getMeasuredHeight()/2);

Log.d(TAG, "onLayout changed:"+changed+" buttonDiametre:"+buttonDiametre);

for(int n=0; n< this.getChildCount(); n++){
     View v = getChildAt(n);

     if (v instanceof TextView) {

         v.layout(centerOfView.x-buttonDiametre/2, centerOfView.y-buttonDiametre/2, centerOfView.x+buttonDiametre/2, centerOfView.y+buttonDiametre/2);
         ViewGroup.LayoutParams textViewParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

         v.setLayoutParams(textViewParams);


         TextView txt = (TextView)v;
         txt.setGravity(Gravity.CENTER);
        }
 }
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
Log.d(TAG, "onMeasure");

int width = getMeasuredWidth();
int height = getMeasuredHeight();

buttonDiametre =  (int) (this.getMeasuredWidth()/4);
Log.d(TAG, "buttonDiametre:"+buttonDiametre+" getChildCount:"+getChildCount());

for (int i = 0; i < getChildCount(); i++) {
    View child = getChildAt(i);

    child.measure(buttonDiametre, buttonDiametre);
}

setMeasuredDimension(width, height);
}

With this try to override onMeasure and onLayout, I see no changes except that the text has lost it center horizontal align. The text is now on top left even with setGravity set to center.

Otherwise, my textbox that are in a square form display well on the different positions. I know i have put them in center but i animate them later to get in correct pposition.

1

There are 1 answers

3
romtsn On

You need to set your TextView height to MATCH_PARENT, then it will center text vertically, too:

TextView myTextView = new TextView(mContext);
myTextView.setBackgroundColor(0xFFFF9900);
myTextView.layout(left, top, right, bottom);

ViewGroup.LayoutParams textViewParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
myTextView.setLayoutParams(textViewParams);

myTextView.setGravity(Gravity.CENTER); // with this, the text is centered horizontally but is still on top. There is plenty of space below
this.addView(myTextView);