【问题标题】:TextView setGravity not working (ignored) with ViewGroup programmaticallyTextView setGravity 无法以编程方式与 ViewGroup 一起工作(忽略)
【发布时间】:2016-11-02 18:19:58
【问题描述】:

我需要完全控制视图的布局,所以我使用 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));

【问题讨论】:

  • 您对measure 的调用应该采用从MeasureSpec#makeMeasureSpec 返回的参数,而不是简单的整数
  • 我认为您的TextView 具有wrap_content,因为它是默认设置。这意味着您可能看不到重力的影响。给它一个宽度和高度或者重量
  • @pskink 这就是答案!谢谢:)

标签: android textview gravity viewgroup programmatically


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-26
    • 2016-07-09
    • 1970-01-01
    相关资源
    最近更新 更多