#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++;
}
}
```
网友评论