文本视图不会以编程方式将高度更新为wrap_content



我希望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

您的问题可能是文本的高度返回 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);
}
});

最新更新