項目要求一個可拖拽的gridview功能,主要是能夠長按圖標,而後手指移動到對應位置,鬆開後圖標移動到對應手指鬆開的位置,後面的圖標依次挪移一個position。git
/**
* 長按的Runnable
*/
private Runnable mLongClickRunable = new Runnable() {
@Override
public void run() {
isDrag = true;
//mVibrator.vibrate(200);
//隱藏該item
mDragView.setVisibility(INVISIBLE);
//在點擊的地方建立並顯示item鏡像
createDragView(mDragBitmap, mDownX, mDownY);
}
};
/**
* 當moveY的值大於向上滾動的邊界值,觸發GridView自動向上滾動
* 當moveY的值小於向下滾動的邊界值,觸犯GridView自動向下滾動
* 不然不進行滾動
*/
private Runnable mScrollRunbale = new Runnable() {
@Override
public void run() {
int scrollY = 0;
if (mMoveY > mUpScrollBorder){
scrollY = mSpeed;
mHandler.postDelayed(mScrollRunbale,25);
}else if (mMoveY < mDownScrollBorder){
scrollY = -mSpeed;
mHandler.postDelayed(mScrollRunbale,25);
}else {
scrollY = 0;
mHandler.removeCallbacks(mScrollRunbale);
}
smoothScrollBy(scrollY,10);
}
};
複製代碼
/************************對外提供的接口***************************************/
public boolean isDrag() {
return isDrag;
}
//設置是否可拖拽
public void setDrag(boolean drag) {
isDrag = drag;
}
public long getDragResponseMs() {
return mDragResponseMs;
}
//設置長按響應時長
public void setDragResponseMs(long mDragResponseMs) {
this.mDragResponseMs = mDragResponseMs;
}
public void setOnItemChangeListener(OnItemChangeListener changeListener) {
this.changeListener = changeListener;
}
/******************************************************************************/
複製代碼
DragGridView dragGridView = findViewById(R.id.dgv);
dragGridView.setNumColumns(NUM_COLUMNS);
initData();
mMoreColorTypeAdapter = new MoreColorTypeAdapter(this, true, data, NUM_COLUMNS);
dragGridView.setAdapter(mMoreColorTypeAdapter);
dragGridView.setOnItemClickListener(this);
dragGridView.setOnItemChangeListener(new DragGridView.OnItemChangeListener() {
@Override
public void onChange(int from, int to) {
Data dataBean = data.get(from);
//直接交互
//Collections.swap(dataSourceList,from,to);
//非直接交互 這裏的處理須要注意下 排序交換
if(from < to){
for(int i = from; i < to; i++){
Collections.swap(data, i, i + 1);
}
}else if(from > to){
for(int i = from; i > to; i--){
Collections.swap(data, i, i - 1);
}
}
data.set(to, dataBean);
mMoreColorTypeAdapter.notifyDataSetChanged();
}
@Override
public void onStop() {
//拖動中止
}
});
複製代碼
源碼下載地址github