I want for the TextView
height to be wrap_content
, and then add an extra space, say 8dp
. I tried this:
textView.getLayoutParams().height = ViewGroup.LayoutParams.WRAP_CONTENT;
textView.setText("Hello world!");
textView.requestLayout();
textView.setHeight(textView.getHeight() + Math.round(convertDpToPx(8)));
but the height is being set to 8dp
instead of WRAP_CONENT + 8dp
Your problem is probably the height of your text returns 0, because You are trying to get it's height before it has drawn. So you need to use addOnGlobalLayoutListener to get the height of view after it has drawn. Like this,
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);
}
});