package com.hqzn.view; import android.content.Context; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.widget.FrameLayout; import android.widget.ScrollView; import android.widget.Scroller; import android.widget.TextView; /** * Created by Administrator on 2016/9/27. */ public class SidingItem extends FrameLayout{ private View view; private TextView tv; private int viewWidth; private int tvWidth; private int hight; private Scroller scroller; public SidingItem(Context context, AttributeSet attrs) { super(context, attrs); scroller=new Scroller(context); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); viewWidth=view.getMeasuredWidth(); tvWidth=tv.getMeasuredWidth(); hight=getHeight(); } @Override protected void onLayout(boolean b, int i, int i1, int i2, int i3) { tv.layout(0,0,tvWidth,hight); view.layout(tvWidth,0,viewWidth+tvWidth,hight); } @Override protected void onFinishInflate() { super.onFinishInflate(); tv= (TextView) getChildAt(0); view=getChildAt(1); } int lastx; @Override public boolean onTouchEvent(MotionEvent event) { super.onTouchEvent(event); int eventx= (int) event.getRawX(); switch (event.getAction()){ case MotionEvent.ACTION_DOWN: lastx= eventx; break; case MotionEvent.ACTION_MOVE: int disx=eventx-lastx; int toScrollX = getScrollX() - disx; System.out.println(toScrollX); // 屏蔽非法值 if (toScrollX < 0) { toScrollX = 0; }else if(toScrollX > viewWidth){ toScrollX = viewWidth; } // scrollTo(toScrollX, 0);// 也可以 scrollTo(toScrollX, getScrollY()); // 重新付值 lastx = eventx; break; case MotionEvent.ACTION_UP: int totallScrollX = getScrollX(); if(totallScrollX < viewWidth/2){ System.out.println("totallScrollX < menuWidth/2"); closeMenu(); }else{ System.out.println("totallScrollX >= menuWidth/2"); openMenu(); } break; } return true; } private void closeMenu() { scroller.startScroll(getScrollX(),getScrollY(),0-getScrollX(),getScrollY()); invalidate();// 会导致 执行 computeScroll } private void openMenu(){ scroller.startScroll(getScrollX(),getScrollY(),viewWidth-getScrollX(),getScrollY()); invalidate();// 会导致 执行 computeScroll } @Override public void computeScroll() { super.computeScroll(); if (scroller.computeScrollOffset()) { scrollTo(scroller.getCurrX(), scroller.getCurrY()); System.out.println("滚动完成"); invalidate();// 强制重绘制 } } }
自定义组合控件之滑动item+删除
最新推荐文章于 2021-03-03 10:24:59 发布