Android LinearLayout with drag and drop to reorder.
An Android
LinearLayoutthat supports draggable and swappable child
Views.
Why bother doing drag & swap in a
LinearLayoutwhen there are so many solutions for
ListView?
ListAdapters. By default, works like a
LinearLayout.
ScrollViewcontainer.
Add it to your project using Gradle:
compile 'com.jmedeisis:draglinearlayout:1.1.0'
The
DragLinearLayoutcan be used in place of any
LinearLayout. However, by default, children will not be draggable. To set an existing
Viewas draggable, use
DragLinearLayout#setViewDraggable(View, View), passing in the child
Viewand a (non-null!)
Viewthat will act as the handle for dragging it (this can be the
Viewitself).
XML layout file:
<textview android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/text"></textview> <imageview android:layout_width="match_parent" android:layout_height="120dp" android:scaletype="centerCrop" android:src="@drawable/image"></imageview> <button android:id="@+id/button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/button_text"></button>
</com.jmedeisis.draglinearlayout.draglinearlayout>
Enabling drag & swap for all child views:
DragLinearLayout dragLinearLayout = (DragLinearLayout) findViewById(R.id.container); for(int i = 0; i < dragLinearLayout.getChildCount(); i++){ View child = dragLinearLayout.getChildAt(i); // the child will act as its own drag handle dragLinearLayout.setViewDraggable(child, child); }
Use
#addDragView(View, View),
#addDragView(View, View, int)and
#removeDragView(View)to manage draggable children dynamically:
final View view = View.inflate(context, R.layout.view_layout, null); dragLinearLayout.addDragView(view, view.findViewById(R.id.view_drag_handle));// ..
dragLinearLayout.removeDragView(view);
Attach an
OnViewSwapListenerwith
#setOnViewSwapListener(OnViewSwapListener)to detect changes to the ordering of child
Views:
dragLinearLayout.setOnViewSwapListener(new DragLinearLayout.OnViewSwapListener() { @Override public void onSwap(View firstView, int firstPosition, View secondView, int secondPosition) { // update data, etc.. } });
When placing the
DragLinearLayoutinside a
ScrollView, call
#setContainerScrollView(ScrollView)to enable the user to scroll while dragging a child view.
For best visual results, use children that have opaque backgrounds. Furthermore, do not use horizontal padding for the
DragLinearLayout; instead, let children apply their own horizontal padding.
Refer to the included sample activity project for a demonstration of the above usage techniques and more.
LinearLayout#VERTICALorientation.
This project is licensed under the terms of the MIT license. You may find a copy of the license in the included
LICENSEfile.