2013-06-03 38 views
1

我們遇到了以下問題ViewTextView的引力應該水平和垂直居中文本,但文本只是水平居中並粘在頂部。怎麼了?自定義佈局和TextView的重力(水平重力工作,但垂直失敗)

public class TestLayout extends ViewGroup { 
    private TextView textView; 

    public TestLayout(Context context, AttributeSet attrs) { 
     super(context, attrs); 

     textView = new TextView(context); 
     textView.setText("Hello world."); 
     textView.setGravity(Gravity.CENTER); 
     addView(textView); 
    } 
    @Override 
    protected void onLayout(boolean changed, int l, int t, int r, int b) { 
     textView.layout(0, 0, r - l, b - t); 
    } 
} 

回答

2

我們找到了解決方案。我們需要在佈局的子項上調用measure()

@Override 
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
    super.onMeasure(widthMeasureSpec, heightMeasureSpec); 
    textView.measure(widthMeasureSpec, heightMeasureSpec); 
} 
+0

上帝保佑你! – lespommes