上一篇文章自定义viewgroup(1)地址:https://www.jb51.net/article/100608.htm
这里直接代码:
package com.example.libingyuan.horizontallistview.ScrollViewGroup; import android.content.Context; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.Scroller; /** * 自定义ViewGroup * 在横向布局的基础上,增加啦滚动效果,但是没有边界限制 */ public class ScrollViewGroup extends ViewGroup { private Scroller mScroller; private float mLastMotiOnX= 0; public ScrollViewGroup(Context context) { this(context, null); } public ScrollViewGroup(Context context, AttributeSet attrs) { this(context, attrs, 0); } public ScrollViewGroup(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } private void init(Context context) { mScroller = new Scroller(context); } @Override public void computeScroll() { if (mScroller.computeScrollOffset()) { scrollTo(mScroller.getCurrX(), mScroller.getCurrY()); postInvalidate(); } } @Override public boolean onTouchEvent(MotionEvent event) { // TODO Auto-generated method stub int action = event.getAction(); float x = event.getX(); switch (action) { case MotionEvent.ACTION_DOWN: if (!mScroller.isFinished()) { mScroller.abortAnimation(); } mLastMotiOnX= event.getX(); break; case MotionEvent.ACTION_MOVE: float delt = mLastMotionX - x; mLastMotiOnX= x; scrollBy((int) delt, 0); break; case MotionEvent.ACTION_UP: invalidate(); break; default: break; } return true; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { //重新设置宽高 this.setMeasuredDimension(measureWidth(widthMeasureSpec, heightMeasureSpec), measureHeight(widthMeasureSpec, heightMeasureSpec)); } /** * 测量宽度 */ private int measureWidth(int widthMeasureSpec, int heightMeasureSpec) { // 宽度 int sizeWidth = MeasureSpec.getSize(widthMeasureSpec); int modeWidth = MeasureSpec.getMode(widthMeasureSpec); //父控件的宽(wrap_content) int width = 0; int childCount = getChildCount(); //重新测量子view的宽度,以及最大高度 for (int i = 0; i
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。