具有动态maxHeight的自定义android视图

时间:2019-06-26 12:10:52

标签: android android-view android-cardview android-orientation onmeasure

我有一个自定义的android视图(从MaterialCardView继承)。我想动态设置其max_height

if the view wants height of  x < 648dp then set the max_height to be 648dp
if the view wants height of  x >= 648 then set the max_height to be 600dp 

基于此post,我已覆盖onMeasure

       @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    ...
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int effectiveMaxHeight = getEffectiveMaxHeight(heightSize);
    switch (heightMode) {
      case MeasureSpec.AT_MOST:
        heightMeasureSpec =
            MeasureSpec.makeMeasureSpec(
                Math.min(heightSize, effectiveMaxHeight), MeasureSpec.AT_MOST);
        break;
      case MeasureSpec.UNSPECIFIED:
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(effectiveMaxHeight, MeasureSpec.AT_MOST);
        break;
      case MeasureSpec.EXACTLY:
        heightMeasureSpec =
            MeasureSpec.makeMeasureSpec(
                Math.min(heightSize, effectiveMaxHeight), MeasureSpec.EXACTLY);
        break;
    }
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
  }

  private int getEffectiveMaxHeight(int heightSize) {
    int extendedMaxHeight =
        getContext().getResources().getDimensionPixelSize(R.dimen.popover_extended_max_height);
    return (heightSize >= extendedMaxHeight)
        ? getContext().getResources().getDimensionPixelSize(R.dimen.popover_max_height)
        : extendedMaxHeight;
  }

但是,当我调试时,我总是看到启用滚动视图的高度是572dp。无论内容多长。

我已检查并且滚动视图本身没有fixed heightmax_height

我还应该仔细检查什么?

0 个答案:

没有答案