catalogue

  • 01. Drag and drop needs to be implemented
  • 02. Several important methods are illustrated
  • 03. Simple implementation ideas
  • 04. Optimization of drag effect
  • 05. Complete code display

Good news

  • Summary of blog notes [March 2016 to present], including Java basic and in-depth knowledge points, Android technology blog, Python learning notes, etc., including the summary of bugs encountered in daily development, of course, I also collected a lot of interview questions in my spare time, updated, maintained and corrected for a long time, and continued to improve… Open source files are in Markdown format! At the same time, ALSO open source life blog, from 12 years, accumulated a total of N [nearly 1 million words, gradually moved to the Internet], reprint please indicate the source, thank you!
  • Link address:Github.com/yangchong21…
  • If you feel good, you can star, thank you! Of course, also welcome to put forward suggestions, everything starts from small, quantitative change causes qualitative change!

01. Drag and drop needs to be implemented

  • Drag and drop functions are shown below
    • Hold and drag item to switch positions with other items
    • Hold down the icon on the right of an item and drag it to switch positions with other items
    • Left slide item becomes transparent and shrinks. When it exceeds the screen, other items are added
    • Right slide item to become transparent and zoom out. When it exceeds the screen, other items are added

02. Several important methods are illustrated

  • Several important methods are illustrated
    • You need a custom class to implement the ItemTouchHelper.Callback class and override several of the methods
    IsLongPressDragEnabled isItemViewSwipeEnabled isItemViewSwipeEnabled isItemViewSwipeEnabled isItemViewSwipeEnabled getMovementFlags When the user drags or drags an Item, we need to tell the system which direction to drag or drag OnMove is called back when the Item is being dragged onSwiped onSelectedChanged is triggered when the Item is being dragged or swipedCopy the code

03. Simple implementation ideas

  • Code ideas in several methods
    • To achieve the above functional requirements, in the getMovementFlags method, when the user drags or slides an Item, we need to tell the system the direction of the slide or drag. LinearLayoutManager and GridLayoutManager support drag and drop and slide delete, so we can distinguish the response based on the layout manager.
    • The onMove method handles the drag-and-drop callback logic, so when is it called? Called when an Item is moved to the position of another Item by drag-and-sort. Handle the deleted logic in the onSwiped method [when Item is swiped out of sight]. To reduce the coupling of the code, it can be handed over to external processing via an interface listener callback.
  • Drag up and down to swap positions with other items
    • Itemtouchhelper. Callback itself does not have the function of interchanging the location of two items, but RecyclerView does. We can swap the location of the current item with that of another item when the item is dragged. Call notifyItemMoved() of RecyclerView to refresh the layout. At the same time, because RecyclerView has its own item animation, the above interaction can be completed.
  • Other items are added when you slide out of the screen
    • Delete the corresponding data when item slides out of the screen, and then call notifyItemRemoved() of RecyclerView to refresh the layout.

04. Optimization of drag effect

  • Drag and drop optimization
    • Itemtouchhelper.callback has methods for both states: onSelectedChanged() and clearView(). So optimization can actually be handled in these two methods.
    • Swiping left and right makes the opacity of the Item lighter and smaller. How do I do that? There is only one method in itemTouchHelper. Callback that gets the displacement of the item as it is dragged or slid, and that is the onChildDraw() method, which animates the item gradient and zoom properties.
    • If there is a problem, a blank item will be left after deletion according to the above method. Then why does this situation occur? The RecyclerView item (itemView) is used over and over again. In the onChildDraw() method, the itemView is transparent and minified. There are only a few ItemViews in a list. When the two transparently reduced ItemViews are used again, the ratio of transparency to height is already set to 0. The solution is also simple. Set the opacity and height ratio of the itemView back

05. Complete code display

  • GitHub address of the code: github.com/yangchong21…
  • The complete code is shown below
    / * * * < pre > * @ author Yang Chong * blog: https://github.com/yangchong211 * time: 2017/5/2 * desc: * revise: Refer to Yan Zhengjie's blog: https://blog.csdn.net/yanzhenjie1003/article/details/51935982 * </pre> */ public class ItemTouchHelpCallback extends ItemTouchHelper. Callback {/ * * * Item correction operation, to update the UI and data sources * / private OnItemTouchCallbackListener OnItemTouchCallbackListener;  /** * private Boolean isCanDrag =false; / / private Boolean isCanSwipe =false; /** * private int color = 0; public ItemTouchHelpCallback(OnItemTouchCallbackListener onItemTouchCallbackListener) { this.onItemTouchCallbackListener  = onItemTouchCallbackListener; } /** * Sets whether it can be dragged ** @param canDrag yestrue, nofalse
         */
        public void setDragEnable(boolean canDrag) { isCanDrag = canDrag; } /** * Sets whether it can be swiped ** @param canSwipe yestrue, nofalse
         */
        public void setSwipeEnable(boolean canSwipe) { isCanSwipe = canSwipe; } /** * set drag item color * @param color */ public voidsetColor(@ColorInt int color){ this.color = color; } /** * whether Item can be dragged when pressed ** @return                      true
         */
        @Override
        public boolean isLongPressDragEnabled() {
            returnisCanDrag; } /** * Whether the Item can be swiped (H: left/right, V: up/down) * isItemViewSwipeEnabled() whether the return value can be dragged and sorted,trueYou can,falseDo not * @return                      true
         */
        @Override
        public boolean isItemViewSwipeEnabled() {
            returnisCanSwipe; } /** * When the user drags or slides an Item, we need to tell the system the direction of the slide or drag. * wipeFlags: Flags for actions that are perpendicular to the scrolling direction of a list (e.g. up and down for a vertical list, left and right for a horizontal list) If you don't want to drag up and down, you can set dragFlags = 0 * if you don't want to drag left and right, */ @override public int getMovementFlags(@nonNULL) */ @override public int getMovementFlags(@nonNULL) RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) { RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();if(layoutManager instanceof GridLayoutManager) {// flag If 0, Equivalent to the function is closed int dragFlag = ItemTouchHelper. LEFT | ItemTouchHelper. RIGHT | ItemTouchHelper. UP | ItemTouchHelper. DOWN; int swipeFlag = 0; // create makereturn makeMovementFlags(dragFlag, swipeFlag);
            } else if(layoutManager instanceof LinearLayoutManager) { LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layoutManager; int orientation = linearLayoutManager.getOrientation(); int dragFlag = 0; int swipeFlag = 0; // A horizontal ListView and a vertical ListViewif (orientation == LinearLayoutManager.HORIZONTAL) {
                    swipeFlag = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
                    dragFlag = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
                } else if(" orientation = = LinearLayoutManager. VERTICAL) {/ / if it is a VERTICAL layout, Equivalent to a ListView dragFlag = ItemTouchHelper. UP | ItemTouchHelper. DOWN; swipeFlag = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT; } // The first argument is to drag flag and the second is to slide flagreturn makeMovementFlags(dragFlag, swipeFlag);
            }
            return0; } @param recyclerView recyclerView @param srcViewHolder The viewHolder of the Item being dragged * @param TargetViewHolder viewHolder * @ of the other item below the currently dragged itemreturn@override public Boolean change (@nonnull RecyclerView RecyclerView, @NonNull RecyclerView.ViewHolder srcViewHolder, @NonNull RecyclerView.ViewHolder targetViewHolder) {if(onItemTouchCallbackListener ! = null) { int srcPosition = srcViewHolder.getAdapterPosition(); int targetPosition = targetViewHolder.getAdapterPosition();return onItemTouchCallbackListener.onMove(srcPosition, targetPosition);
            }
            return false; } /** * triggered when the item slides out (vertical lists are slippage, * * @param viewHolder viewHolder @param direction The direction of the slide */ @override public void onSwiped(@nonnull) RecyclerView.ViewHolder viewHolder, int direction) {if(onItemTouchCallbackListener ! = null) { onItemTouchCallbackListener.onSwiped(viewHolder.getAdapterPosition()); } /** * Triggered when an item is dragged or slid ** @param viewHolder viewHolder * @param actionState Current item status */ @override public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) { super.onSelectedChanged(viewHolder, actionState); // The background color should change whether it is dragged or sideslipif(actionState ! = ItemTouchHelper.ACTION_STATE_IDLE) {if (color==0){
                    viewHolder.itemView.setBackgroundColor(viewHolder.itemView.getContext()
                            .getResources().getColor(android.R.color.darker_gray));
                }else{ viewHolder.itemView.setBackgroundColor(color); }} /** * trigger when the interactive animation of item ends ** @param recyclerView recyclerView * @param viewHolder viewHolder */ @override public void  clearView(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) { super.clearView(recyclerView, viewHolder); viewHolder.itemView.setBackgroundColor(viewHolder.itemView.getContext().getResources() .getColor(android.R.color.white)); viewHolder.itemView.setAlpha(1); viewHolder.itemView.setScaleY(1); } @Override public void onChildDraw(@NonNull Canvas c, @NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder,float dX, float dY, int actionState, boolean isCurrentlyActive) {
            super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
            if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
                floatvalue = 1 - Math.abs(dX) / viewHolder.itemView.getWidth(); viewHolder.itemView.setAlpha(value); viewHolder.itemView.setScaleY(value); }} public interface OnItemTouchCallbackListener {/ * * * * * when an Item is deleted sliding @ param adapterPosition Item position * / void onSwiped(int adapterPosition); ** @param srcPosition position of the dragged Item * @param targetPosition Position of the destination Item * @returnThe developer should return after processing the actiontrue, the developer returns without processingfalse*/ boolean onMove(int srcPosition, int targetPosition); }}Copy the code
  • How to use the code shown below
    ItemTouchHelpCallback callback = new ItemTouchHelpCallback((srcPosition, targetPosition) -> {
            if(imageBeans ! = null) {try {// Change the position of Item in the data source. Change the position at the beginning and end of the collections. swap(imageBeans, srcPosition, targetPosition); Madapter. notifyItemMoved(srcPosition, targetPosition); // Update the position of the Item in the UI. } catch (Exception e){ e.printStackTrace(); }return true;
            }
            return true;
        });
    callback.setDragEnable(true);
    callback.setSwipeEnable(true); callback.setColor(this.getResources().getColor(R.color.base_background_block)); ItemTouchHelper ItemTouchHelper = new ItemTouchHelper(callback); Try {/ / associated recyclerView, a helper objects can only corresponds to a recyclerView itemTouchHelper. AttachToRecyclerView (recyclerView); }catch (Exception e){ e.printStackTrace(); }Copy the code

Open source library address [integration of most recyclerView use cases, can directly download demo] :Github.com/yangchong21…

  • RecyclerView Complex packaging library
    • Almost the fusion of the blog series in the vast majority of knowledge, welcome to see the blog again practice, step by step from the simple implementation of powerful library
  • 01.RecyclerView
    • RecycleView structure, RecyclerView simple usage introduction
  • 02.Adapter
    • Recyclerview. Adapter play the role of the general use of rewrite method description, data change notification observer mode, view. NotifyChanged (); The source code
  • 03.ViewHolder
    • Stop calling onCreateViewHolder when the number of ViewHolder objects is sufficient
  • 04.LayoutManager
    • What does LayoutManager do? SetLayoutManager source code analysis
  • 05.SnapHelper
    • SnapHelper is an important method to Fling.
  • 06.ItemTouchHelper
  • 07.SpanSizeLookup
    • How is SpanSizeLookup used to contain lists, 2-column grids, and 3-column grids elegantly implemented?
  • 08.ItemDecoration
    • ItemDecoration, addItemDecoration() source code analysis
  • 09.RecycledViewPool
    • RecyclerViewPool is used to share the View between multiple recyclerViews.
  • 11.RecyclerView pull loading
    • Add a sliding event of recyclerView, pull up to load paging data, set the bottom footer layout of the pull up load, show and hide the Footer layout
  • RecyclerView Cache principle
    • RecyclerView performance optimization to say complex also complex, such as layout optimization, cache, preloading, reuse pool, refresh data and so on
  • SnapHelper source code analysis
    • SnapHelper is designed to support the alignment of RecyclerView by calculating the alignment of the specified TargetView in RecyclerView or any pixel in the container.
  • 16. Customize SnapHelper
    • Custom SnapHelper
  • 19. Customize ItemDecoration line
    • Need a custom class implements RecyclerView. ItemDecoration class, and choose to rewrite the appropriate method
  • RecyclerView problem summary
    • GetLayoutPosition () and getAdapterPosition()
  • 23.RecyclerView sliding conflict
    • 01 how to judge the RecyclerView control to slide to the top and bottom
    • RecyclerView nested RecyclerView items automatically roll Bug
    • 03.ScrollView nested RecyclerView sliding conflict
    • 04.ViewPager nested level RecyclerView horizontal slide after the end do not slide ViewPager
    • 05.RecyclerView nested RecyclerView sliding conflict problem
    • 06 RecyclerView use Glide loading picture caused by picture confusion to solve the problem
  • ScrollView nested RecyclerView problem
    • To embed one or more recyclerViews in NestedScrollView, there will be sliding conflicts, focus preemption, display incompletion and so on. How to deal with it?

The other is introduced

01. About blog summary links

  • 1. Tech blog round-up
  • 2. Open source project summary
  • 3. Life Blog Summary
  • 4. Himalayan audio summary
  • 5. Other summaries

02. About my blog

  • My personal website: www.yczbj.org, www.ycbjie.cn
  • Github:github.com/yangchong21…
  • Zhihu: www.zhihu.com/people/yczb…
  • Jane: www.jianshu.com/u/b7b2c6ed9…
  • csdn:my.csdn.net/m0_37700275
  • The Himalayan listening: www.ximalaya.com/zhubo/71989…
  • Source: China my.oschina.net/zbj1618/blo…
  • Soak in the days of online: www.jcodecraeer.com/member/cont.
  • Email address: [email protected]
  • Blog: ali cloud yq.aliyun.com/users/artic… 239.headeruserinfo.3.dT4bcV
  • Segmentfault headline: segmentfault.com/u/xiangjian…
  • The Denver nuggets: juejin. Cn/user / 197877…

Code examples:Github.com/yangchong21…