Detailed explanation of the method of list sideslip deletion by Android programming

  • 2021-08-12 03:40:29
  • OfStack

In this paper, an example is given to describe the method of list sideslip deletion by Android programming. Share it for your reference, as follows:

Today, I suddenly remembered the sliding deletion function of the list. Some drop-down refresh frames will also bring this sideslip deletion function. For example, some listview and recycleview refresh frames all have this function. The purpose of writing this blog today is how to realize sideslip deletion without relying on these frames. If the list frame you have used does not have sideslip deletion, how to add sideslip deletion function separately.

Summary: The article I wrote today is about how to add sideslip deletion function to the list separately, instead of relying on a list framework for sideslip deletion, that is to say, if necessary, you can simply add this sideslip deletion function to your list. The main implementation is the custom list of items container view, to achieve the monitoring of gestures, so as to achieve the effect of deleting buttons through the sideslip of gestures.

Ok, let's start the text. . .

First, give the code for the custom entry container control:

Please take a good look at the comments inside, help you quickly understand the implementation of this class, and achieve your custom! !


public class DragListItem extends LinearLayout {
  private Context mContext;
  private View mHidenDragView;
  private LinearLayout mContentView;// Will wrap the actual content 
  private LinearLayout mHidenLayout;
  private Scroller mScroller;
  private int mLastX, mLastY;
  private int mDragOutWidth;// The distance of complete sideslip 
  private double mfraction = 0.75;// Critical point of triggering automatic sideslip 
  private boolean isDrag = false;
  public DragListItem(Context context) {
    super(context);
    mContext = context;
    initView();
  }
  public DragListItem(Context context, AttributeSet attrs) {
    super(context, attrs);
    mContext = context;
    initView();
  }
  private void initView() {
    setOrientation(HORIZONTAL);
    //merge Come in the whole listItem Here, you can define the display layout of the Delete button, and modify it according to your preferences 
    mHidenDragView = View.inflate(mContext, R.layout.hide_drag_item, this);
    mContentView = (LinearLayout) mHidenDragView.findViewById(R.id.show_content_view);
    mHidenLayout = (LinearLayout) mHidenDragView.findViewById(R.id.hide_view);
    mScroller = new Scroller(mContext);
    // Assign the width of the hidden deletion layout to the value of the boundary, which can be modified arbitrarily according to your own needs 
    mDragOutWidth = dip2px(mContext, 120);
  }
  public static int dip2px(Context context, float dpValue) {
    final float scale = context.getResources().getDisplayMetrics().density;
    return (int) (dpValue * scale + 0.5f);
  }
  /**
   *  According to the events passed in, the sideslip logic is judged here, so as to realize the effect function of deleting button sliding out when sideslip is realized 
   */
  public void onDragTouchEvent(MotionEvent event) {
    if (isDrag) {// Setting items can not be clicked when the finger slides horizontally 
      setClickable(false);
    } else {
      setClickable(true);
    }
    int x = (int) event.getX();
    int y = (int) event.getY();
    int scrollX = getScrollX();// Upper left corner of mobile phone screen x Value of axis  - view The upper left corner of the x Value of axis 
    switch (event.getAction()) {
      case MotionEvent.ACTION_DOWN:
        if (!mScroller.isFinished()) {
          mScroller.abortAnimation();
        }
        break;
      case MotionEvent.ACTION_MOVE:
        hsaMove = true;
        int deltaX = x - mLastX;
        int deltaY = y - mLastY;
        // When the longitudinal slip is larger than the transverse slip, the sideslip effect will not be punished 
        //  Add here 100 Is to make the sideslip of the item easier to trigger, and you can adjust the value according to your own needs 
        if (Math.abs(deltaX) + 100 < Math.abs(deltaY))
        {
          break;
        }
        if (deltaX != 0) {// Fingers are sliding laterally 
          isDrag = true;
          int newScrollX = scrollX - deltaX;// When this value becomes small, view View slides to the left 
          if (newScrollX < 0) {// Keep greater than or equal to 0 , equal to 0 Hour view Upper left corner x Value and the upper left corner of the screen x Value coincidence 
            newScrollX = 0;
            setClickable(true);
          } else if (newScrollX > mDragOutWidth) {// When the boundary of the hidden layout is reached,   You can't sideslip any more 
            newScrollX = mDragOutWidth;
          }
          scrollTo(newScrollX, 0);
        }
        break;
      case MotionEvent.ACTION_UP:
        hsaMove = false;
      default:
        int finalScrollX = 0;
        // Slide left enough to automatically slide out to delete the layout 
        //  Otherwise, the hidden delete layout is automatically retracted 
        if (scrollX > mDragOutWidth * mfraction) {
          finalScrollX = mDragOutWidth;
          autoScrollToX(finalScrollX, 500);
        } else {
          rollBack();
          isDrag = false;
        }
        break;
    }
    mLastX = x;
    mLastY = y;
  }
  private boolean hsaMove = false;// Whether the item has monitored the sliding of the gesture is used as a condition for judging whether to slide the item left and right 1
  public boolean isHsaMove() {
    return hsaMove;
  }
  public void setHsaMove(boolean hsaMove) {
    this.hsaMove = hsaMove;
  }
  public void setIsDrag(boolean isDrag) {
    this.isDrag = isDrag;
  }
  /**
   *  Automatic rollback to closed state 
   */
  public void rollBack() {
    if (getScrollX() != 0) {
      autoScrollToX(0, 100);
      new Handler().postDelayed(new Runnable() {
        public void run() {
          setClickable(true);
          isDrag = false;// Set the status to false , no sideslip 
          hsaMove = false;// After the state is reset, set whether to slide over to no slide over 
        }
      }, 10);
    }
  }
  private void autoScrollToX(int finalX, int duration) {
    mScroller.startScroll(getScrollX(), 0, finalX - getScrollX(), 0, duration);
    invalidate();
  }
  public boolean getDragState() {
    return isDrag;
  }
  @Override
  public void computeScroll() {
    if (mScroller.computeScrollOffset()) {
      scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
      postInvalidate();
    }
  }
  /**
   *  Change the text of a hidden page 
   */
  public void setFirstHidenView(CharSequence charSequence) {
    TextView textView = (TextView) mHidenLayout.findViewById(R.id.hide_delete);
    textView.setText(charSequence);
  }
  /**
   *  Add a view of hidden pages to users (not just delete them) 
   */
  public void addHidenView(TextView view) {
    mHidenLayout.addView(view);
  }
  /**
   *  Set for the user listItem The actual content of 
   */
  public void setContentView(View view) {
    mContentView.addView(view);
  }
  public double getMfraction() {
    return mfraction;
  }
  public void setMfraction(double mfraction) {
    this.mfraction = mfraction;
  }
}

Give a simple explanation of this control:

In the above custom control, through comments, you can clearly see that the layout of the original items is wrapped in the custom container, and then intercept finger events to deal with sideslip events, so that the deletion layout is displayed and hidden, and sideslip deletion is realized.

Of course, this implementation principle is still very simple, and people who understand it can make customized modifications according to their own needs to achieve the effects and functions they need.

For example: Hidden layout can be arbitrarily set, so not 1 is the deletion function, as long as the need to achieve sideslip can rely on this control to achieve quickly and simply.

The following is the layout file that this control needs to load: (This is the effect of my project, and different people can make different modifications according to their own needs)


<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical">
  <!--  What is actually displayed -->
  <LinearLayout
    android:id="@+id/show_content_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    >
  </LinearLayout>
  <!-- Hidden deletion behind -->
  <LinearLayout
    android:id="@+id/hide_view"
    android:layout_width="120dp"
    android:layout_height="match_parent"
    android:background="@android:color/holo_red_dark"
    android:orientation="horizontal">
    <TextView
      android:id="@+id/hide_delete"
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      android:layout_gravity="center"
      android:layout_weight="1"
      android:gravity="center"
      android:text=" Delete "
      android:textSize="20sp" />
  </LinearLayout>
</merge>

Ok, this custom control code and layout files have been provided to you, the principle I have already said, is to rely on this custom control to achieve the sideslip deletion effect.

The following is a simple listview as an example to show you the simple use of this control: (do this in the adapter processing is good)


@Override
public View getView(int position, View convertView, ViewGroup parent) {
  final ViewHolder viewHolder;
  DragListItem dragListItem = (DragListItem) convertView;
  if (dragListItem == null) {
    View view = layoutInflater.inflate(R.layout.list_item_drag, parent, false);
    dragListItem = new DragListItem(mContext);
    dragListItem.setContentView(view);
    viewHolder = new ViewHolder(dragListItem);
    dragListItem.setTag(viewHolder);
  } else {
    viewHolder = (ViewHolder) dragListItem.getTag();
  }
  dragListItem.rollBack();
  dragListItem.setOnClickListener(new View.OnClickListener() {// Add a click event to an entry 
    @Override
    public void onClick(View v) {
    }
  });
  viewHolder.hideItem.setOnClickListener(new View.OnClickListener() {// Set click events for hidden layouts   For example, click to delete the function 
     @Override
    public void onClick(View v) {
      Toast.makeText(mContext, " Delete ", Toast.LENGTH_SHORT).show();
    }
  });
  return dragListItem;
}

In this way, the sideslip deletion function is realized in the list! ! !

Although I use listview as an example, as long as the Android technology can be colleagues, can see that this implementation can be integrated in any list to achieve a simple and quick sideslip removal effect! !

For more readers interested in Android related content, please check the topics on this site: "Introduction and Advanced Tutorial of Android Development", "Summary of Android Debugging Skills and Common Problem Solutions", "Summary of Android Basic Component Usage", "Summary of View Skills in Android View", "Summary of layout Skills in Android Layout" and "Summary of Android Control Usage"

I hope this article is helpful to everyone's Android programming.


Related articles: