自定义ViewGroup中的Textview重力

时间:2015-06-26 06:37:24

标签: android textview gravity viewgroup

我的自定义视图扩展为ViewGroup而且我不知道为什么,但我无法垂直居中TextView的文本。

我就是这样做的:

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);

我已经在LinearLayoutRelativeLayout上花了很多时间,我应该错过什么但是什么?

编辑:

@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);
}

尝试覆盖onMeasure和onLayout,我看到没有任何变化,除了文本丢失了中心水平对齐。即使setGravity设置为居中,文本现在位于左上角。

否则,我的方形文本框在不同的位置上显示良好。我知道我把它们放在了中心,但我后来为它们制作动画以获得正确的位置。

1 个答案:

答案 0 :(得分:0)

您需要将TextView高度设置为MATCH_PARENT,然后它也会垂直居中:

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);