標籤:android 圖片 拖拽
1.使用RecyclerView
使用RecyclerView可以輕鬆實現圖片切換時的動畫過程,這點要好於GridView。
2. 拖拽的實現
繼承View.OnDragListener,對拖拽過程中進行操作,
Action_drag_started 擷取到操作的Item
Action_Drag_location 根據每個停留的位置判斷是否交換item的位置。
Action_Drag_ended 跟新位置
抽象類別,為recyclerView 增加onItemTouchListener和onScrollListener, 記錄onTouch的item,並在拖拽過程中判斷recyclerview是否可以滾動,從而在拖拽的item快到邊界時滾動recyclerView,使可以與本來在螢幕上不可見的item進行交換位置。
ViewHolder 實現startDrag方法
2.itemDecoration
為recyclerview item增加divider,可以有兩種方式,覆蓋onDraw方法繪製itemDivider,或者覆蓋getItemOffsets方法,使item之間可以分隔開。
3.GridlayoutManager
當recyclerview嵌入到scrollview中時,需要複寫LayoutManager,在這裡複寫其中的onMeasure方法,需要計算每個item的高度或者寬度進行疊加,當recyclerview中item很多時,不要採用這種方式,回導致view不能複用,其中在計算item高度時,需要加上每個item的itemOffsets,查看recyclerview的源碼發現,無法直接擷取到item的offsets,最終採用反射的方式擷取到其值:
try { Method method = recyclerView.getClass().getDeclaredMethod("getItemDecorInsetsForChild",View.class); method.setAccessible(true); final Rect insets = (Rect)method.invoke(recyclerView, child); itemDecorationHeight = heightUsed + insets.height(); itemDecorationWidth = widthUsed + insets.width();} catch (NoSuchMethodException e){ Log.d("FullGridLayoutManager","no method found");}catch(IllegalAccessException e){ Log.d("FullGridLayoutManager","IllegalAccessException");}catch (InvocationTargetException e){ Log.d("FullGridLayoutManager","InvocationTargetException");}
android 實現圖片選擇拖拽控制項