简介
Space是一个轻量级View子类,可以用在布局中创建组件之间的间隙。
用法
<android.support.v4.widget.Space
android:layout_width="match_parent"
android:layout_height="50dp" />
说明
/**
* Space is a lightweight {@link View} subclass that may be used to create gaps between components
* in general purpose layouts.
*/
public class Space extends View {
public Space(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
if (getVisibility() == VISIBLE) {
setVisibility(INVISIBLE);
}
}
public Space(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public Space(Context context) {
this(context, null);
}
/**
* Draw nothing.
*
* @param canvas an unused parameter.
*/
@Override
public void draw(Canvas canvas) {
}
/**
* Compare to: {@link View#getDefaultSize(int, int)}
* If mode is AT_MOST, return the child size instead of the parent size
* (unless it is too big).
*/
private static int getDefaultSize2(int size, int measureSpec) {
int result = size;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
switch (specMode) {
case MeasureSpec.UNSPECIFIED:
result = size;
break;
case MeasureSpec.AT_MOST:
result = Math.min(size, specSize);
break;
case MeasureSpec.EXACTLY:
result = specSize;
break;
}
return result;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(
getDefaultSize2(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize2(getSuggestedMinimumHeight(), heightMeasureSpec));
}
}
查看源码会发现Space控件onDraw方法没有实现。
Space控件在布局中只占位置,而不去绘制渲染。所以在组件之前填充间隙效率会很高,有助于提高性能。正是因为onDraw()
为空,对该 view 没有做任务绘制渲染,所以不能对 Space 设置背景色。