【发布时间】:2012-02-07 17:42:53
【问题描述】:
有什么办法可以避免将 layout_width 和 layout_height 参数添加到我的自定义视图中?我知道有一些内置的 android 视图您不必为其提供这些属性。
【问题讨论】:
有什么办法可以避免将 layout_width 和 layout_height 参数添加到我的自定义视图中?我知道有一些内置的 android 视图您不必为其提供这些属性。
【问题讨论】:
决定它是否可以/应该提供这些属性不是视图的责任。父 ViewGroup 规定这些属性是否是必需的。例如,TableRow 使它们成为可选的。其他布局(LinearLayout、FrameLayout 等)需要这些参数。
【讨论】:
您何时不想使用高度和宽度参数?我不确定,但我认为这会导致它们甚至不会出现在布局上?
参考这里http://developer.android.com/guide/topics/ui/declaring-layout.html#layout-params
【讨论】:
来自同一位 Reference Dave 建议。
所有视图组都包含宽度和高度(layout_width 和 layout_height),并且每个视图都需要定义它们。许多 LayoutParams 还包括可选的边距和边框。
看起来,你必须。
【讨论】:
ViewGroup,但它说它是abstract class (developer.android.com/reference/android/view/ViewGroup.html) 扩展它的类,然而,它们实现了layout_height 和layout_width
如果您想要减少通用和冗余属性,那么您应该尝试样式化。
开发者指南here.
【讨论】:
问题在于ViewGroup.LayoutParams.setBaseAttributes() 使用严格的getLayoutDimension(int, String)。
您需要扩展您需要的任何 LayoutParams 并覆盖 setBaseAttributes。
在里面你可以手动设置宽度和高度,或者使用更宽松的getLayoutDimension(int, int)。最后,您必须在使用自己的 LayoutParams 的布局类中覆盖。
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LayoutParams(getContext(), attrs);
}
public static class LayoutParams extends FrameLayout.LayoutParams {
public LayoutParams(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void setBaseAttributes(TypedArray a, int widthAttr, int heightAttr) {
width = a.getLayoutDimension(widthAttr, WRAP_CONTENT);
height = a.getLayoutDimension(heightAttr, WRAP_CONTENT);
}
}
【讨论】: