Home > Java > javaTutorial > Customized view in Android to achieve side sliding effect

Customized view in Android to achieve side sliding effect

高洛峰
Release: 2017-01-13 10:34:55
Original
1174 people have browsed it

Rendering:

Customized view in Android to achieve side sliding effect

#Looking at the Internet, there are two views spliced ​​together. By default, the right view is not displayed. When moving horizontally, the right view is displayed. However, the effect on the latest version of QQ is not like this, but it feels very good, so it is better to use a high imitation.

Knowledge points:

1. Usage of ViewDragHelper;
2. Resolution of sliding conflicts;
3. Customized viewgroup.

ViewDragHelper has been out for a long time. I believe everyone is familiar with it. If you are not familiar with it, google it. Here are a few simple methods to use it.

1. tryCaptureView(View child , int pointerId): Determine which child view can slide

2. getViewHorizontalDragRange(View child): Translated in my poor English, it is 'returns the size of the child view that can be moved in the horizontal direction, in pixels is the unit. When 0 is returned, it means that dragging cannot be done in the horizontal direction The position

4. onViewPositionChanged(View changedView, int left, int top,

int dx, int dy): Callback when the view is to be captured and the position changes due to dragging or setting


Its basic usage is:

public SwipeLayout(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init();
  }
  private void init() {
    viewDragHelper = ViewDragHelper.create(this, callback);
  }
   public boolean onInterceptTouchEvent(MotionEvent ev) {
    boolean result = viewDragHelper.shouldInterceptTouchEvent(ev);
   }
   public boolean onTouchEvent(MotionEvent event) {
    viewDragHelper.processTouchEvent(event);
    return true;
  }
Copy after login

1), create in the constructor

2), determine whether to intercept in onInterceptTouchEvent

3), in onTouchEvent comes out event

Okay, the most difficult to understand thing has been solved. Next, let’s look at the specific implementation:

First, look at the layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:orientation="vertical" >
  <scrollviewgroup.lly.com.swiplayout.SwipeLayout
    android:id="@+id/swipeLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
    <!-- delete区域的布局 -->
    <include layout="@layout/layout_delete" />
    <!-- item内容的布局 -->
    <include layout="@layout/layout_content" />
  </scrollviewgroup.lly.com.swiplayout.SwipeLayout>
</LinearLayout>
Copy after login

There’s nothing to say about this. A custom viewgroup contains two sub-controls.

Then let’s take a look at how SwipeLayout is implemented:

@Override
  protected void onFinishInflate() {
    super.onFinishInflate();
    deleteView = getChildAt(0);
    contentView = getChildAt(1);
  }
  @Override
  protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    deleteHeight = deleteView.getMeasuredHeight();
    deleteWidth = deleteView.getMeasuredWidth();
    contentWidth = contentView.getMeasuredWidth();
    screenWidth = getWidth();
  }
  @Override
  protected void onLayout(boolean changed, int left, int top, int right,
              int bottom) {
    // super.onLayout(changed, left, top, right, bottom);
    deleteView.layout(screenWidth - deleteWidth, 0, (screenWidth - deleteWidth)
        + deleteWidth, deleteHeight);
    contentView.layout(0, 0, contentWidth, deleteHeight);
  }
Copy after login

The above code performs some initialization operations. Focus on the onlayout. What we inherit is framelayout. Here we first draw deleteView and let He is on the right, and then changes a layer of contentView on top, so that only the contentView will be displayed when displayed.

Next look at the ontouch method

public boolean onTouchEvent(MotionEvent event) {
    //如果当前有打开的,则下面的逻辑不能执行
    if(!SwipeLayoutManager.getInstance().isShouldSwipe(this)){
      requestDisallowInterceptTouchEvent(true);
      return true;
    }
    switch (event.getAction()) {
      case MotionEvent.ACTION_DOWN:
        downX = event.getX();
        downY = event.getY();
        break;
      case MotionEvent.ACTION_MOVE:
        //1.获取x和y方向移动的距离
        float moveX = event.getX();
        float moveY = event.getY();
        float delatX = moveX - downX;//x方向移动的距离
        float delatY = moveY - downY;//y方向移动的距离
        if(Math.abs(delatX)>Math.abs(delatY)){
          //表示移动是偏向于水平方向,那么应该SwipeLayout应该处理,请求父view不要拦截
          requestDisallowInterceptTouchEvent(true);
        }
        //更新downX,downY
        downX = moveX;
        downY = moveY;
        break;
      case MotionEvent.ACTION_UP:
        break;
    }
    viewDragHelper.processTouchEvent(event);
    return true;
  }
Copy after login

The above is mainly about handling event conflicts. When it moves horizontally, it requests the parent view not to intercept it.

The next thing is the key point

private ViewDragHelper.Callback callback = new ViewDragHelper.Callback() {
    @Override
    public boolean tryCaptureView(View child, int pointerId) {
      return child==contentView;
    }
    @Override
    public int getViewHorizontalDragRange(View child) {
      return deleteWidth;
    }
    @Override
    public int clampViewPositionHorizontal(View child, int left, int dx) {
      if(child==contentView){
        if(left>0)left = 0;
        if(left<-deleteWidth)left = -deleteWidth;
      }
      return left;
    }
    @Override
    public void onViewPositionChanged(View changedView, int left, int top,
                     int dx, int dy) {
      super.onViewPositionChanged(changedView, left, top, dx, dy);
      //判断开和关闭的逻辑
      if(contentView.getLeft()==0 && currentState!=SwipeState.Close){
        //说明应该将state更改为关闭
        currentState = SwipeState.Close;
        //回调接口关闭的方法
        if(listener!=null){
          listener.onClose(getTag());
        }
        //说明当前的SwipeLayout已经关闭,需要让Manager清空一下
        SwipeLayoutManager.getInstance().clearCurrentLayout();
      }else if (contentView.getLeft()==-deleteWidth && currentState!=SwipeState.Open) {
        //说明应该将state更改为开
        currentState = SwipeState.Open;
        //回调接口打开的方法
        if(listener!=null){
          listener.onOpen(getTag());
        }
        //当前的Swipelayout已经打开,需要让Manager记录一下下
        SwipeLayoutManager.getInstance().setSwipeLayout(SwipeLayout.this);
      }
    }
    @Override
    public void onViewReleased(View releasedChild, float xvel, float yvel) {
      super.onViewReleased(releasedChild, xvel, yvel);
      if(contentView.getLeft()<-deleteWidth/2){
        //应该打开
        open();
      }else {
        //应该关闭
        close();
      }
    }
  };
Copy after login

We have all mentioned the method in the above code at the beginning. Let’s take a look. In tryCaptureView, we allow the contentView to slide. In getViewHorizontalDragRange The sliding range of Zhongquedong is deleteWidth. The boundary is restricted in clampViewPositionHorizontal. The status is updated in onViewPositionChanged. Finally, when the finger is lifted, the view automatically rolls back.

/**
  * 打开的方法
  */
 public void open() {
   viewDragHelper.smoothSlideViewTo(contentView,-deleteWidth,contentView.getTop());
   ViewCompat.postInvalidateOnAnimation(SwipeLayout.this);
 }
 /**
  * 关闭的方法
  */
 public void close() {
   viewDragHelper.smoothSlideViewTo(contentView,0,contentView.getTop());
   ViewCompat.postInvalidateOnAnimation(SwipeLayout.this);
 };
 public void computeScroll() {
   if(viewDragHelper.continueSettling(true)){
     ViewCompat.postInvalidateOnAnimation(this);
   }
 }
Copy after login

Be sure to pay attention here Rewrite the computeScroll method, otherwise the sliding effect will stop moving.

This custom framelayout is now complete

But we found a problem. When we slide up and down in the view that has been slid out, the deleteView of this view is still displayed, so we still have to add it to the activity Let’s deal with it:

recyView.setOnScrollListener(new RecyclerView.OnScrollListener() {
     @Override
     public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
       super.onScrollStateChanged(recyclerView, newState);
     }
     @Override
     public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
       super.onScrolled(recyclerView, dx, dy);
       if(dy>0 || dy<0){
         SwipeLayoutManager.getInstance().closeCurrentLayout();
       }
     }
   });
Copy after login

When this RecyclerView slides up and down, reset the subview.

Call it a day.


ps: It was originally implemented in listview in eclipse, but considering that Google no longer supports eclipse, and listview is about to be replaced by RecyclerView, so I finally switched to Android studio and implemented it with RecyclerView. set.

The above is the custom view in Android introduced by the editor to achieve the side sliding effect. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. . I would also like to thank you all for your support of the PHP Chinese website!

For more articles related to customizing views in Android to achieve side-sliding effects, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template