android view实现横向滑动选择

本文实例为大家分享了android view实现横向滑动选择的具体代码,供大家参考,具体内容如下

做文字编辑,从网上找来的。

HorizontalScrollSelectView:

  public boolean mAlwaysOverrideTouch = true;
  protected ListAdapter mAdapter;
  private int mLeftViewIndex = -1;
  private int mRightViewIndex = 0;
  protected int mCurrentX;
  protected int mNextX;
  private int mMaxX = Integer.MAX_VALUE;
  private int mDisplayOffset = 0;
  protected Scroller mScroller;
  private GestureDetector mGesture;
  private Queue<View> mRemovedViewQueue = new LinkedList<View>();
  private OnItemSelectedListener mOnItemSelected;
  private OnItemClickListener mOnItemClicked;
  private OnItemLongClickListener mOnItemLongClicked;
  private OnScrollListener mScrollListener;
  /**
   * 选中item时图片
   */
  private Drawable mDrawable;
  private boolean mDataChanged = false;
  private Context context;
  private boolean scrollerFalg1 = false;
  private boolean scrollerFalg2 = false;
  private int position = 0x7f020000;

  public HorizontalScrollSelectView(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.context = context;
    initView();
  }

  private synchronized void initView() {
    mLeftViewIndex = -1;
    mRightViewIndex = 0;
    mDisplayOffset = 0;
    mCurrentX = 0;
    mNextX = 0;
    mMaxX = Integer.MAX_VALUE;
    mScroller = new Scroller(getContext());
    mGesture = new GestureDetector(getContext(), mOnGesture);
  }

  public void setMScrollListener(OnScrollListener listener) {
    mScrollListener = listener;
  }

  @Override
  public void setOnItemSelectedListener(OnItemSelectedListener listener) {
    mOnItemSelected = listener;
  }

  @Override
  public void setOnItemClickListener(OnItemClickListener listener) {
    mOnItemClicked = listener;
  }

  @Override
  public void setOnItemLongClickListener(OnItemLongClickListener listener) {
    mOnItemLongClicked = listener;
  }

  /**
   * 设置选中状态时的图片
   *
   * @param mDrawable
   */
  public void setSelectBitmap(Drawable mDrawable) {
    this.mDrawable = mDrawable;
  }

  private DataSetObserver mDataObserver = new DataSetObserver() {

    @Override
    public void onChanged() {
      synchronized (HorizontalScrollSelectView.this) {
        mDataChanged = true;
      }
      invalidate();
      requestLayout();
    }

    @Override
    public void onInvalidated() {
      reset();
      invalidate();
      requestLayout();
    }

  };

  @Override
  public ListAdapter getAdapter() {
    return mAdapter;
  }

  @Override
  public View getSelectedView() {
    //TODO: implement
    return null;
  }

  @Override
  public void setAdapter(ListAdapter adapter) {
    if (mAdapter != null) {
      mAdapter.unregisterDataSetObserver(mDataObserver);
    }
    mAdapter = adapter;
    mAdapter.registerDataSetObserver(mDataObserver);
    reset();
  }

  private synchronized void reset() {
    initView();
    removeAllViewsInLayout();
    requestLayout();
  }

  @Override
  public void setSelection(int position) {
    //TODO: implement
    int positionX = position * this.getWidth();
    int maxWidth = this.getChildCount() * this.getWidth();
    if (positionX <= 0) {
      positionX = 0;
    }
    if (positionX > maxWidth) {
      positionX = maxWidth;
    }
    scrollTo(positionX);
  }

  private void addAndMeasureChild(final View child, int viewPos) {
    LayoutParams params = child.getLayoutParams();
    if (params == null) {
      params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    }

    addViewInLayout(child, viewPos, params, true);
    child.measure(MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.AT_MOST),
        MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.AT_MOST));
  }

  @SuppressLint("NewApi")
  @Override
  protected synchronized void onLayout(boolean changed, int left, int top, int right, int bottom) {
    super.onLayout(changed, left, top, right, bottom);

    if (mAdapter == null) {
      return;
    }

    if (mDataChanged) {
      int oldCurrentX = mCurrentX;
      initView();
      removeAllViewsInLayout();
      mNextX = oldCurrentX;
      mDataChanged = false;
    }

    if (mScroller.computeScrollOffset()) {
      int scrollx = mScroller.getCurrX();
      mNextX = scrollx;
    }

// if(mNextX <= 0){
//  mNextX = 0;
//  mScroller.forceFinished(true);
// }
// if(mNextX >= mMaxX) {
//  mNextX = mMaxX;
//  mScroller.forceFinished(true);
// }

    int dx = mCurrentX - mNextX;

    removeNonVisibleItems(dx);
    fillList(dx);
    positionItems(dx);
// Log.e("onlayout", "mLeftViewIndex"+(mLeftViewIndex+1));
    mCurrentX = mNextX;

    if (!mScroller.isFinished()) {
      post(new Runnable() {
        @Override
        public void run() {
          requestLayout();
        }
      });

    } else {
      if (scrollerFalg1 || (!scrollerFalg1 && scrollerFalg2)) {
        View chid = getChildAt(0);
        if (chid != null) {
          mDisplayOffset = 0;
          positionItems(0);
          if (mDrawable != null) {
            getChildAt(2).setBackground(mDrawable);
          }
          if (mScrollListener != null) {
            int position = (int) getChildAt(2).getTag(this.position);
            mScrollListener.onScrollSelectItem(this, position);
          }
        }

      }
    }

  }

  /**
   * 获取屏幕宽度
   *
   * @param context
   * @return
   */
  public static int getSecreenWidth(Context context) {
    DisplayMetrics dm = new DisplayMetrics();
    dm = context.getResources().getDisplayMetrics();
    int screenWidth = dm.widthPixels;
    return screenWidth / 5;
  }

  private void fillList(final int dx) {
    int edge = 0;
    View child = getChildAt(0);
    if (child != null) {
      edge = child.getLeft();
    }
    fillListLeft(edge, dx);

    edge = 0;
    child = getChildAt(getChildCount() - 1);
    if (child != null) {
      edge = child.getRight();
    }
    fillListRight(edge, dx);

  }

  private void fillListRight(int rightEdge, final int dx) {
    //&& mRightViewIndex < mAdapter.getCount()
    while (rightEdge + dx < getWidth()) {
      if (mRightViewIndex >= mAdapter.getCount()) {
        mRightViewIndex = 0;
      }
      View child = mAdapter.getView(mRightViewIndex, mRemovedViewQueue.poll(), this);
      child.setTag(position, mRightViewIndex);
      addAndMeasureChild(child, -1);
      rightEdge += child.getMeasuredWidth();

//  if(mRightViewIndex == mAdapter.getCount()-1) {
//  mMaxX = mCurrentX + rightEdge - getWidth();
//  }
//
//  if (mMaxX < 0) {
//  mMaxX = 0;
//  }
      mRightViewIndex++;
    }

  }

  private void fillListLeft(int leftEdge, final int dx) {
    //&& mLeftViewIndex >= 0
    while (leftEdge + dx > 0) {
      if (mLeftViewIndex <= -1) {
        mLeftViewIndex = mAdapter.getCount() - 1;
      }
      View child = mAdapter.getView(mLeftViewIndex, mRemovedViewQueue.poll(), this);
      child.setTag(position, mLeftViewIndex);
      addAndMeasureChild(child, 0);
      leftEdge -= child.getMeasuredWidth();
      mLeftViewIndex--;
      mDisplayOffset -= child.getMeasuredWidth();
    }
  }

  private void removeNonVisibleItems(final int dx) {
    View child = getChildAt(0);
    while (child != null && child.getRight() + dx <= 0) {
      mDisplayOffset += child.getMeasuredWidth();
      mRemovedViewQueue.offer(child);
      removeViewInLayout(child);
      mLeftViewIndex++;
      if (mLeftViewIndex >= mAdapter.getCount()) {
        mLeftViewIndex = 0;
      }
      child = getChildAt(0);

    }

    child = getChildAt(getChildCount() - 1);
    while (child != null && child.getLeft() + dx >= getWidth()) {
      mRemovedViewQueue.offer(child);
      removeViewInLayout(child);
      mRightViewIndex--;
      if (mRightViewIndex <= -1) {
        mRightViewIndex = mAdapter.getCount() - 1;
      }
      child = getChildAt(getChildCount() - 1);
    }
  }

  private void positionItems(final int dx) {
    if (getChildCount() > 0) {
      mDisplayOffset += dx;
      int left = mDisplayOffset;
      for (int i = 0; i < getChildCount(); i++) {
        View child = getChildAt(i);
        getChildAt(2).setBackground(null);
        int childWidth = child.getMeasuredWidth();
        child.layout(left, 0, left + childWidth, child.getMeasuredHeight());
        left += childWidth + child.getPaddingRight();
      }
    }
  }

  public synchronized void scrollTo(int x) {
    mScroller.startScroll(mNextX, 0, x - mNextX, 0);
    requestLayout();
  }

  @Override
  public boolean dispatchTouchEvent(MotionEvent ev) {
    boolean handled = super.dispatchTouchEvent(ev);
    handled |= mGesture.onTouchEvent(ev);

    switch (ev.getAction()) {
      case MotionEvent.ACTION_UP:
        scrollerFalg2 = true;
        requestLayout();
        break;
      default:
        break;
    }
    return handled;
  }

  protected boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
               float velocityY) {
    synchronized (HorizontalScrollSelectView.this) {
      //mNextX
      mScroller.fling(mNextX, 0, (int) -velocityX, 0, Integer.MIN_VALUE, mMaxX, 0, 0);
    }
    requestLayout();
    scrollerFalg1 = true;
    return true;
  }

  protected boolean onDown(MotionEvent e) {
    mScroller.forceFinished(true);
    return true;
  }

  public interface OnScrollListener {
    /**
     * 互动过程中选中的item
     *
     * @param position
     */
    public void onScrollSelectItem(ViewGroup viewGroup, int position);

  }

  private OnGestureListener mOnGesture = new GestureDetector.SimpleOnGestureListener() {

    @Override
    public boolean onDown(MotionEvent e) {
      return HorizontalScrollSelectView.this.onDown(e);
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                float velocityY) {
      return HorizontalScrollSelectView.this.onFling(e1, e2, velocityX, velocityY);
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2,
                float distanceX, float distanceY) {

      synchronized (HorizontalScrollSelectView.this) {
        mNextX += (int) distanceX;
      }
      requestLayout();
      scrollerFalg1 = false;
      scrollerFalg2 = false;
      return true;
    }

    @Override
    public void onShowPress(MotionEvent e) {
      super.onShowPress(e);
    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
      Log.e("onSingleTapUp", "mLeftViewIndex" + (mLeftViewIndex + 1));
//  scrollerFalg=true;
      return super.onSingleTapUp(e);
    }

    @Override
    public boolean onSingleTapConfirmed(MotionEvent e) {
      for (int i = 0; i < getChildCount(); i++) {
        View child = getChildAt(i);
        if (isEventWithinView(e, child)) {
          if (mOnItemClicked != null) {
            mOnItemClicked.onItemClick(HorizontalScrollSelectView.this, child, mLeftViewIndex + 1 + i, mAdapter.getItemId(mLeftViewIndex + 1 + i));
          }
          if (mOnItemSelected != null) {
            mOnItemSelected.onItemSelected(HorizontalScrollSelectView.this, child, mLeftViewIndex + 1 + i, mAdapter.getItemId(mLeftViewIndex + 1 + i));
          }
          break;
        }

      }
      return true;
    }

    @Override
    public void onLongPress(MotionEvent e) {
      int childCount = getChildCount();
      for (int i = 0; i < childCount; i++) {
        View child = getChildAt(i);
        if (isEventWithinView(e, child)) {
          if (mOnItemLongClicked != null) {
            mOnItemLongClicked.onItemLongClick(HorizontalScrollSelectView.this, child, mLeftViewIndex + 1 + i, mAdapter.getItemId(mLeftViewIndex + 1 + i));
          }
          break;
        }

      }
    }

    private boolean isEventWithinView(MotionEvent e, View child) {
      Rect viewRect = new Rect();
      int[] childPosition = new int[2];
      child.getLocationOnScreen(childPosition);
      int left = childPosition[0];
      int right = left + child.getWidth();
      int top = childPosition[1];
      int bottom = top + child.getHeight();
      viewRect.set(left, top, right, bottom);
      return viewRect.contains((int) e.getRawX(), (int) e.getRawY());
    }
  };

demo截图:

源码下载:android view实现横向滑动选择

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • Android实现滑动选择控件实例代码

    前言 最近做了个滑动选择的小控件,拿出来给大家分享一下,先上图 运行效果 实现步骤 这里分解为3个动作:Down.Move.Up来进行分析,博主文采不好,大家直接看流程图吧!! 代码分析 前置知识 1.这个地方使用的是RecyclerView的代码,使用RecyclerView只能使用LinearLayoutManager,ListView的运行效果稍微要比RecyclerView差一些 //这里使用dispatchTouchEvent,因为onTouchEvent容易被OnTouchListe

  • Android自定义标尺滑动选择值效果

    本文实例为大家分享了Android实现滑动标尺选择值,效果图 1.自定义属性attrs.xml <declare-styleable name="RulerView"> <attr name="textColor" format="color" /> <attr name="textSize" format="dimension" /> <attr name=&qu

  • Android自定义View实现左右滑动选择出生年份

    自定义view的第三篇,模仿的是微博运动界面的个人出生日期设置view,先看看我的效果图: 支持设置初始年份,左右滑动选择出生年份,对应的TextView的值也会改变.这个动画效果弄了好久,感觉还是比较生硬,与微博那个还是有点区别.大家有改进的方案,欢迎一起交流. 自定义View四部曲,这里依旧是这个套路,看看怎么实现的. 1.自定义view的属性: 在res/values/ 下建立一个attrs.xml , 在里面定义我们的属性以及声明我们的整个样式. <?xml version="1.

  • android view实现横向滑动选择

    本文实例为大家分享了android view实现横向滑动选择的具体代码,供大家参考,具体内容如下 做文字编辑,从网上找来的. HorizontalScrollSelectView: public boolean mAlwaysOverrideTouch = true; protected ListAdapter mAdapter; private int mLeftViewIndex = -1; private int mRightViewIndex = 0; protected int mCu

  • Android仿天猫横向滑动指示器功能的实现

    Android开发中会有很多很新奇的交互,比如天猫商城的首页头部的分类,使用的是GridLayoutManager+横向指示器实现的,效果如下图. 那对于这种效果要如何实现呢?最简单的方式就是使用RecyclerView+GridLayoutManager,我们知道RecyclerView可以实现九宫格,接下来就是通过RecyclerView控制指示器的显示位置,逻辑实现如下: 计算出RecyclerView划出屏幕的距离w1和剩余宽度w2的比例y,y = w1 / (总宽度w3 - 可使视区域

  • Android ScrollView嵌套横向滑动控件时冲突问题

    前言:今天在开发的时候遇到这样的问题,最外层是ScrollView,里面嵌套了一个横向滑动的日历控件,在滑动日历的时候很卡顿.看到这种问题,自然而然的就会想到scrollview和其他可滑动控件的冲突问题. 解决思路 用户的左右滑动操作被最外层的scrollView控件处理掉了,所以只要让scrollview对左右滑动事件不监听,让其子控件处理左右滑动事件 .重写scrollview的onInterceptTouchEvent方法,当上下滑动时不处理即可. 代码如下 public void se

  • Android开发基于ViewPager+GridView实现仿大众点评横向滑动功能

    先给大家展示下效果图,如果大家大家感觉不错,请参考实现思路及代码 1 ViewPager类提供了多界面切换的新效果. 新效果有如下特征: [1] 当前显示一组界面中的其中一个界面. [2] 当用户通过左右滑动界面时,当前的屏幕显示当前界面和下一个界面的一部分. [3]滑动结束后,界面自动跳转到当前选择的界面中 2 介绍里面几个比较重要的方法与接口 1,OnPageChangeListener ViewPager页面进行切换监听接口 其中我们经常要实现public void onPageSelec

  • Android自定义横向滑动菜单的实现

    本文讲述了Android自定义横向滑动菜单的实现.分享给大家供大家参考,具体如下: 前言 开发安卓过程中,经常会用到标题栏的样式,有时候传统方式不能满足开发者的需要,这时候就需要自定义控件来实现.(注意:本文提供思路,有关键代码,但是代码不全) 标题栏说明 自定义标题栏ColumnHorizontalScrollView继承HorizontalScrollView 这个安卓原生的控件,HorizontalScrollView是一种FrameLayout(框架布局),其子项被滚动查看时是整体移动的

  • Android 自定义 HorizontalScrollView 打造多图片OOM 的横向滑动效果(实例代码)

    自从Gallery被谷歌废弃以后,Google推荐使用ViewPager和HorizontalScrollView来实现Gallery的效果.的确HorizontalScrollView可以实现Gallery的效果,但是HorizontalScrollView存在一个很大的问题,如果你仅是用来展示少量的图片,应该是没问题的,但是如果我希望HorizontalScrollView可以想ViewPager一样,既可以绑定数据集(动态改变图片),还能做到,不管多少图片都不会OOM(ViewPager内

  • Android中RecyclerView实现横向滑动代码

    RecyclerView 是Android L版本中新添加的一个用来取代ListView的SDK,它的灵活性与可替代性比listview更好.本文给大家介绍Android中RecyclerView实现横向滑动代码,一起看看吧. android.support.v7.widget.RecyclerView 功能:RecyclerView横向滑动 控件:<android.support.v7.widget.RecyclerView /> Java类:RecyclerView.GalleryAdap

  • Android自定义View实现多图片选择控件

    前言 相信很多朋友在开发中都会遇到图片上传的情况,尤其是多图上传,最经典的莫过于微信的图片选择了.所有很多情况下会使用到多图选择,所以就有了这篇文章,今天抽点时间写了个控件.  •支持自定义选择图片的样式  •支持设置图片选择数量  •支持图片预览,删除  •支持图片拍照 先来看看效果 实现分析 假如不定义控件,我们要实现这样一个功能,无非是写个GridView在item点击的时候去显示图片进行选择,在返回界面的时候进行GridView的数据刷新.我们把这些逻辑写在我们自定义的GridView中

随机推荐