MatchParent与活动匹配,而不是与WrapContent Parent

时间:2016-02-14 04:37:41

标签: android android-layout android-custom-view

我有一个适配器布局,在里面我添加了4个使用WrapContent(3x TextView和一个自定义视图)的元素。这3个视图工作正常,但自定义视图与容器(LinearLayout)不匹配,让TextView完成工作以选择此布局的高度。

当我在此自定义视图中使用wrap_content时,会发生这种情况:

Calculus error

我尝试使用此代码来计算此视图的大小,使用:

@Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    int desiredWidth = 100;
    int desiredHeight = 100;

    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);

    int width;
    int height;

    //Measure Width
    if (widthMode == MeasureSpec.EXACTLY) {
      //Must be this size
      width = widthSize;
    } else if (widthMode == MeasureSpec.AT_MOST) {
      //Can't be bigger than...
      width = Math.min(desiredWidth, widthSize);
    } else {
      //Be whatever you want
      width = desiredWidth;
    }

    //Measure Height
    if (heightMode == MeasureSpec.EXACTLY) {
      //Must be this size
      height = heightSize;
    } else if (heightMode == MeasureSpec.AT_MOST) {
      //Can't be bigger than...
      height = Math.min(desiredHeight, heightSize);
    } else {
      //Be whatever you want
      height = desiredHeight;
    }

    setMeasuredDimension(width, height);
  }

但我真的希望这个视图与父级匹配,没有任何其他参数。

我在方法 onMeasure

中尝试了这个
ViewGroup parent = (ViewGroup) getParent();
parent.getHeight; <- Return 0    >:(

任何人都可以帮助我?

0 个答案:

没有答案