android space控件 变成线条,学Android Space控件,只看这篇文章就行了

06765c569f9a

Space

Space is a lightweight View subclass that may be used to create gaps between components in general purpose layouts.

Space 是一个轻量级的 View 子类,可用于在通用布局中的组件之间创建间隙。

介绍

Space经常用于组件之间的缝隙,其draw()为空,减少了绘制渲染的过程。组件之间的距离使用Space会提高了绘制效率,特别是对于动态设置间距会很方便高效。

正是因为draw()为空,对该view没有做任务绘制渲染,所以不能对Space设置背景色。

选择

Space控件在android中有三个,分别是

android.support.v7.widget.Space

android.support.v4.widget.Space

android.widget.Space

其中v7包的Space已经废弃,android.widget.Space是android4.0才添加的,而v4包的Space是为了兼容低版本的 android 系统。但是现在谷歌已经放弃了android2.3和3.0,所以android.support.v4.widget.Space和android.widget.Space任君选择其一,内部实现代码都一样,

源码分析

package android.support.v4.widget;

import android.content.Context;

import android.graphics.Canvas;

import android.util.AttributeSet;

import android.view.View;

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的实现代码很简洁。只是对控件的显示方式默认为INVISIBLE并重新计算view的宽高。

使用

在xml使用。注意,使用v4包的Space需要在gradle中导入v4包,或者导入v7、v13包。因为v7包内含有v4包,v13包内也含有v4包。

android:layout_width="1dp"

android:layout_height="10dp" />

在java代码使用。

Space space = new Space(this);

space.setMinimumWidth(1);

space.setMinimumHeight(10);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值