package com.bobo.viewgroup;
import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.widget.LinearLayout;
public class MyGroupView extends ViewGroup {
private LinearLayout left;
private LinearLayout middle;
private LinearLayout right;
private int measuredWidth;
private int measuredHeight;
/**
*使用XML配置文件显示界面的时候调用
*/
public MyGroupView(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context);
}
/**
*使用代码显示界面的时候调用
*/
public MyGroupView(Context context) {
super(context);
initView(context);
}
// 初始化界面
private void initView(Context context) {
// 给出孩子的宽高
left = new LinearLayout(context);
left.setBackgroundColor(Color.BLUE);
left.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
middle = new LinearLayout(context);
middle.setBackgroundColor(Color.RED);
middle.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
right = new LinearLayout(context);
right.setBackgroundColor(Color.GREEN);
right.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
// 添加孩子到ViewGroup
this.addView(left);
this.addView(middle);
this.addView(right);
}
// 显示界面之前一定要去测量孩子的宽高
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 测量孩子的宽高
left.measure(widthMeasureSpec, heightMeasureSpec);
middle.measure(widthMeasureSpec, heightMeasureSpec);
right.measure(widthMeasureSpec, heightMeasureSpec);
// 获取测量后的宽高(注意只有 先measure才可以getMeasuredWidth)
measuredWidth = left.getMeasuredWidth();
measuredHeight = left.getMeasuredHeight();
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
// 控制孩子的显示位置
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
left.layout(-measuredWidth, 0, 0, measuredHeight);
middle.layout(0, 0, measuredWidth, measuredHeight);
right.layout(measuredWidth, 0, measuredWidth * 2, measuredHeight);
}
int startX;
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
startX = (int) event.getRawX();
break;
case MotionEvent.ACTION_MOVE:
int newX = (int) event.getRawX();
int dx = newX - startX;
// 相对当前位置进行移动
scrollBy(-dx, 0);
// 重新获取当前位置
startX = (int) event.getRawX();
invalidate();//更新
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
}