View自定义属性

#View自定义属性

##1.在style中声明

```

true

```

##2. class中获取对应的属性声明

```

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.XSView);

isVertical = a.getBoolean(R.styleable.XSView_vertical, true);

```

##3.xml中使用对应的属性

```

android:layout_width="wrap_content"

android:layout_height="wrap_content"

app:vertical="true">

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="测试1" />

android:visibility="gone"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="测试2" />

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="测试3" />

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="测试4" />

```

#根据声明属性和布局绘制view

##1 继承自ViewGroup

```

public class XSView extends ViewGroup {

private boolean isVertical = false;

public XSView(Context context) {

this(context, null);

}

public XSView(Context context, AttributeSet attrs) {

this(context, attrs, 0);

}

public XSView(Context context, AttributeSet attrs, int defStyleAttr) {

this(context, attrs, defStyleAttr, 0);

}

public XSView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {

super(context, attrs, defStyleAttr, defStyleRes);

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.XSView);

isVertical = a.getBoolean(R.styleable.XSView_vertical, true);

}

}

```

##2测量View

```

@Override

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

super.onMeasure(widthMeasureSpec, heightMeasureSpec);

measureChildren(widthMeasureSpec, heightMeasureSpec);

}

```

## 3摆放child view

```

@Override

protected void onLayout(boolean changed, int l, int t, int r, int b) {

int childCount = getChildCount();

int left = 0;

int index = 0;

for (int i = 0; i < childCount; i++) {

View child = getChildAt(i);

if (child.getVisibility() == View.GONE) {

continue;

}

int contentWidth = child.getMeasuredWidth() - child.getPaddingLeft() - child.getPaddingRight();

int contentHeight = child.getMeasuredHeight();

if (isVertical) {

child.layout(left + contentWidth * 0, contentHeight * index, contentWidth * (index + 1), contentHeight * (index + 1));

} else {

child.layout(left + contentWidth * index, 0, contentWidth * (index + 1), contentHeight);

}

index++;

}

}

```

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容