我要添加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()
-params =
的第一行崩溃。错误是:
java.lang.ClassCastException: android.view.ViewGroup$LayoutParams cannot be cast to android.view.ViewGroup$MarginLayoutParams
表示在充气期间,充气机创建了LayoutParams而不是MarginLayoutParams。
如何获取MarginLayoutParms或其他包含layout_margin值的变体?
答案 0 :(得分:0)
扩展ViewGroup
的类也必须覆盖generateLayoutParams()
。就我而言:
@Override
public LayoutParams generateLayoutParams (AttributeSet attrs)
{
return new ViewGroup.MarginLayoutParams (getContext(), attrs);
}
,但是您可以扩展LayoutParams
以包含所需的内容,而不必使用MarginLayoutParams
。在展开子视图期间,会调用generateLayoutParams()
。这就是(aha)为什么inflate需要知道父级视图组的原因,即使此时您没有将新的子级添加到父级。
信用确实归@MikeM。谢谢!