【问题标题】:Custom layout and gravity of TextView (horizontal gravity works but vertical fails)TextView 的自定义布局和重力(水平重力有效但垂直失败)
【发布时间】:2013-06-03 16:56:20
【问题描述】:

我们遇到了以下View 的问题。 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);
    }   
}

【问题讨论】:

    标签: android textview gravity


    【解决方案1】:

    我们找到了解决方案。我们需要在布局的子级上调用measure()

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

    【讨论】:

    • 上帝保佑你!!
    猜你喜欢
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多