自定义布局文件 centerLayout 继承自ViewGroup ,这个类是让布局中的子控件在centerLayout 的布局中 水平垂直居中显示,
public class CenterLayout extends ViewGroup {
int groupHeight, groupWidth;
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
Log.i("绘制顺序", this.toString() + "onSizeChanged ");
super.onSizeChanged(w, h, oldw, oldh);
groupHeight = h;
groupWidth = w;
}
public CenterLayout(Context context, AttributeSet attrs) {
super(context, attrs);
Log.i("绘制顺序", this.toString() + "构造方法 ");
// TODO Auto-generated constructor stub
}
// 测量每个子控件
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Log.i("绘制顺序", this.toString() + "onMeasure ");
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// 得到子控件个数
int childCount = this.getChildCount();
for (int i = 0; i < childCount; i++) {
// 得到一个子控件
View childView = this.getChildAt(i);
// 测量子控件
childView.measure(widthMeasureSpec, heightMeasureSpec);
}
}
// 指定子控件如何显示
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
Log.i("绘制顺序", this.toString() + "onLayout ");
// 找到第一个子控件
// View animationView = this.getChildAt(0);
// View shadeView = this.getChildAt(1);
// 模拟出linearLayout
// animationView.layout(0, 0, 90, 90);
// shadeView.layout(0, 90, 480, 90+60);
// frameLayout
// animationView.layout(0, 0, 90, 90);
// shadeView.layout(0, 0, 480, 60);
// animationView.layout(0, 0, 60, 60);
// shadeView.layout(60, 60, 480, 120);
int childCount = this.getChildCount();
int sum = 0;
for (int i = 0; i < childCount; i++) {
View childView = this.getChildAt(i);
// sum = sum + childView.getHeight();
sum = sum + childView.getMeasuredHeight();
}
int top = (groupHeight - sum) / 2;
for (int i = 0; i < childCount; i++) {
View childView = this.getChildAt(i);
int left = (groupWidth - childView.getWidth()) / 2;
int right = left + childView.getMeasuredWidth();
int bottom = top + childView.getMeasuredHeight();
childView.layout(left, top, right, bottom);
top = top + childView.getMeasuredHeight();
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.i("事件处理顺序", this.toString() + " onTouchEvent");
return super.onTouchEvent(event);
}
//分发
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.i("事件处理顺序", this.toString() + " dispatchTouchEvent");
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
Log.i("事件处理顺序", this.toString() + " onInterceptTouchEvent");
return super.onInterceptTouchEvent(ev);
//return true;
}
}
layout 布局文件中
<com.tttttt.all.widget.CenterLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
子控件
子控件
</com.tttttt.all.widget.CenterLayout>