(已经更新了,请看另外一篇)
一.
源码的原理跟上一篇上下切换view是一样的就不解析了
二.源码
public class ViewGp extends ViewGroup {
private Scroller scroller;
private static float cuX,lasX,lasXX;
private static boolean Menuflag=true,MenuShowing=false;
public ViewGp(Context context) {
super(context);
setBackgroundColor(Color.BLACK);
scroller = new Scroller(context);
}
public ViewGp(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public ViewGp(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
@Override
public void computeScroll() {
if(scroller.computeScrollOffset()){
getChildAt(1).layout(scroller.getCurrX(), 0, scroller.getCurrX()+(getChildAt(1).getWidth()), getHeight());
getChildAt(0).layout(scroller.getCurrX()-(getChildAt(1).getWidth())+50, 0, scroller.getCurrX() , getHeight());
postInvalidate();
}
super.computeScroll();
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int viewcount = getChildCount();
for(int count=0;count<viewcount;count++){
View child = getChildAt(count);
int height = child.getMeasuredHeight();
int wdith = child.getMeasuredWidth();
child.layout(0, 0, wdith, height);
if(count==0){
getChildAt(0).layout(0, 0, wdith, height);
}
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(width, height);
for(int i=0;i<getChildCount();i++){
getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec);
}
}
public void ShowMenu(float currN,float currX){
scroller.startScroll((int)currN,0,(int)currX-(int)currN,0);
invalidate();
MenuShowing=true;
}
public void OpenMenu(float currN,float currX){
scroller.startScroll((int)currN,0,(getWidth()-(int)currN-50),0);
invalidate();
Menuflag = false;
MenuShowing=false;
}
public void CloseMenu(float currN,float currX){
scroller.startScroll((int)currN,0,-(int)currN,0);
invalidate();
Menuflag = true;
MenuShowing=false;
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.i("Mainactivity", "---getAction>>"+ev.getAction());
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
lasXX = ev.getX();
break;
case MotionEvent.ACTION_MOVE:
if(Menuflag&&lasXX<50){
cuX = ev.getX();
if(cuX>getWidth()-50){}else{//消除空隙
ShowMenu(cuX,lasX);
}
lasX = ev.getX();
}else if(!Menuflag&&lasXX>getWidth()-50){
cuX = ev.getX();
if(cuX>getWidth()-50){}else{//消除空隙
ShowMenu(cuX,lasX);
}
lasX = ev.getX();
}
break;
case MotionEvent.ACTION_UP:
Log.i("Mainactivity", "---getX>>"+getX());
if(MenuShowing&&ev.getX()<getWidth()/2){
CloseMenu(getX(),0);
}else if(MenuShowing&&ev.getX()>=getWidth()/2){
OpenMenu(ev.getX(),0);
}
break;
default:
break;
}
return super.dispatchTouchEvent(ev);
}
}