TextView setGravity 无法以编程方式与 ViewGroup 一起工作(忽略)

问题描述 投票:0回答:1

我需要完全控制视图的布局,所以我按如下方式使用 ViewGroup:

        ViewGroup wrapper = new ViewGroup(getContext()) {
            @Override
            protected void onLayout(boolean changed, int l, int t, int r, int b) {
                setClipChildren(false);
                for (int c = 0; c < this.getChildCount(); c++) {
                    View v = this.getChildAt(c);
                    ViewGroup.LayoutParams lp = v.getLayoutParams();
                    //Log.d(TAG, "layout " + c + " w:" + lp.width + " h:" + lp.height);
                    v.layout(0, 0, lp.width, lp.height);
                }
            }
        };

        float nextY = dipY;
        for (SwipeMarkdown.Element e : markdown) {
            TextView tv = new TextView(getContext());
            tv.setText(e.text);
            tv.setTextSize(e.fontSize);
            tv.setTextColor(e.textColor);
            tv.setGravity(Gravity.CENTER);// e.textAlignment);
            tv.setBackgroundColor(Color.YELLOW);
            tv.setX(0);
            tv.setY(nextY);
            tv.measure((int)dipW, (int)dipH);
            int mh = tv.getMeasuredHeight();
            nextY = nextY + mh + e.lineSpacing;
            wrapper.addView(tv, new ViewGroup.LayoutParams((int)dipW, (int) mh));
        }

        wrapper.setY((dipH - nextY)/2); // center vertically in self
        viewGroup.addView(wrapper, new ViewGroup.LayoutParams((int) dipW, ViewGroup.LayoutParams.WRAP_CONTENT));
    }

一切正常,除了我无法让 setGravity() 对齐文本。

我错过了什么?

谢谢

更新:@pskink 给了我答案!调用

measure()
需要使用
MeasureSpec
如下:

    tv.measure(View.MeasureSpec.makeMeasureSpec(dipW, View.MeasureSpec.EXACTLY),
               View.MeasureSpec.makeMeasureSpec(dipH, View.MeasureSpec.AT_MOST));
android textview gravity viewgroup
1个回答
0
投票

@pskink 给了我答案!调用 measure() 需要使用 MeasureSpec

© www.soinside.com 2019 - 2024. All rights reserved.