TextView不会以编程方式将高度更新为wrap_content

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

我希望TextView的高度为wrap_content,然后添加一个额外的空格,例如8dp。我试过了:

textView.getLayoutParams().height = ViewGroup.LayoutParams.WRAP_CONTENT;
textView.setText("Hello world!");
textView.requestLayout();

textView.setHeight(textView.getHeight() + Math.round(convertDpToPx(8)));

但是高度被设置为8dp而不是WRAP_CONENT + 8dp

android textview
1个回答
1
投票

您的问题可能是文本的高度返回0,因为您正试图在绘制之前获取其高度。因此,您需要使用addOnGlobalLayoutListener绘制后获取视图的高度。这样,

textView.setText("Hello world!");
    textView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            textView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            ViewGroup.LayoutParams params = textView.getLayoutParams();
            params.height =textView.getHeight() + Math.round(convertDpToPx(8);
            textView.setLayoutParams(params);
        }
    });
© www.soinside.com 2019 - 2024. All rights reserved.