繁体   English   中英

子视图丢失layout_margin

[英]child views losing layout_margin

我要添加LinearLayout作为自定义布局的子级。 LinearLayout具有边距,但是这些边距永远不会进入LayoutParams。

这是LinearLayout的xml

<com.perinote.widgets.LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:orientation="vertical"
  android:layout_marginLeft="@dimen/popup_margin_LR"
  android:layout_marginRight="@dimen/popup_margin_LR"
  android:layout_marginTop="@dimen/popup_margin_TB"
  android:layout_marginBottom="@dimen/popup_margin_TB"
  >

这是将LinearLayout扩展并添加到自定义布局的代码,其中“ this”是自定义布局,它是ViewGroup的扩展:

  public View setContentView (int layoutId)
  {
    LayoutInflater inflater = ((Activity) getContext()).getLayoutInflater();
    ViewGroup v = (ViewGroup) inflater.inflate (layoutId, this, false);
    contentView = v;

    ViewGroup.LayoutParams params = v.getLayoutParams ();
    this.addView (contentView, params);

    return contentView;
  }

最后,这是自定义布局中的onMeasure部分。

  @Override
  protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec)
  {
    ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) contentView.getLayoutParams();

    int contentWidth = MeasureSpec.getSize (widthMeasureSpec);
    int contentHeight = MeasureSpec.getSize (heightMeasureSpec);

    ... some other stuff ...

    // measure contentView.
    int contentWidthSpec = MeasureSpec.makeMeasureSpec (contentWidth, MeasureSpec.AT_MOST);
    int contentHeightSpec = MeasureSpec.makeMeasureSpec (contentHeight, MeasureSpec.AT_MOST);
    contentView.measure (contentWidthSpec, contentHeightSpec);

    setMeasuredDimension (MeasureSpec.getSize (widthMeasureSpec), MeasureSpec.getSize (heightMeasureSpec));
  }

该应用程序在onMeasure()的第一行崩溃onMeasure() params = 错误是:

java.lang.ClassCastException: android.view.ViewGroup$LayoutParams cannot be cast to android.view.ViewGroup$MarginLayoutParams

这表示在充气期间,充气机创建了LayoutParams而不是MarginLayoutParams。

如何获得MarginLayoutParms或其他包含layout_margin值的变体?

扩展ViewGroup的类还必须重写generateLayoutParams() 就我而言:

@Override
public LayoutParams generateLayoutParams (AttributeSet attrs)
{
  return new ViewGroup.MarginLayoutParams (getContext(), attrs);
}

但是您可以扩展LayoutParams以包含所需的内容,而不是使用MarginLayoutParams 在子视图膨胀期间,调用generateLayoutParams() 这就是(aha)为什么inflate需要知道父级视图组的原因,即使此时您没有将新的子级添加到父级。

信贷真的归@MikeM。谢谢!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM