TextView 不会以编程方式将高度更新为 wrap_content
TextView won't update height to wrap_content programmatically
我希望 TextView
高度为 wrap_content
,然后添加一个额外的 space,比如 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
您的问题可能是文本的高度 returns 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);
}
});
我希望 TextView
高度为 wrap_content
,然后添加一个额外的 space,比如 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
您的问题可能是文本的高度 returns 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);
}
});