Accurate way to determine the measured height of a view, even before it changed from GONE to VISIBLE

前端 未结 2 775
有刺的猬
有刺的猬 2021-01-31 11:48

Currently, I have a layout which looks like this. It contains.

  • Title text view, and Price text view, which is visible always.
  • Description Text View
2条回答
  •  长发绾君心
    2021-01-31 12:05

    Your 2nd code snippet is almost correct, but you need to specify pixel sizes - not FILL_PARENT/MATCH_PARENT. This should work:

    v.measure(MeasureSpec.makeMeasureSpec(parentView.getWidth(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(MAX_HEIGHT, MeasureSpec.AT_MOST));
    final int targetHeight = v.getMeasuredHeight();
    

    You'll need to have a reference to the ViewGroup that v is a child of to get its width, and define MAX_HEIGHT (or perhaps use the parent View's height?).

    Also, you should change the height parameters of the two TextViews that are within the horizontal LinearLayout to wrap_content, as using match_parent here may cause problems. The LinearLayout is set to wrap_content, but the two children don't specify a height.

提交回复
热议问题