通过ItemtouchHelper.
packagecom.wds.testdragrecyclerview;
importandroid.support.v7.app.AppCompatActivity;
importandroid.os.Bundle;
importandroid.support.v7.widget.GridLayoutManager;
importandroid.support.v7.widget.RecyclerView;
importandroid.support.v7.widget.helper.ItemTouchHelper;
importandroid.util.Log;
importandroid.view.LayoutInflater;
importandroid.view.View;
importandroid.view.ViewGroup;
importandroid.widget.ImageView;
public classMainActivityextendsAppCompatActivity {
privateRecyclerViewmDragView;
@Override
protected voidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDragView= (RecyclerView) findViewById(R.id.dragview);
mDragView.setLayoutManager(newGridLayoutManager(this,4));
mDragView.setAdapter(newMyAdapter());
ItemTouchHelper helper =newItemTouchHelper(newItemTouchHelper.Callback() {
@Override
public intgetMovementFlags(RecyclerView recyclerView,RecyclerView.ViewHolder viewHolder) {
Log.e("wds","getMovementFlags");
intdragFlag = ItemTouchHelper.LEFT| ItemTouchHelper.DOWN| ItemTouchHelper.UP| ItemTouchHelper.RIGHT;
intswipeFlag = ItemTouchHelper.START| ItemTouchHelper.END;
returnmakeMovementFlags(dragFlag,swipeFlag);
}
@Override
public booleanonMove(RecyclerView recyclerView,RecyclerView.ViewHolder viewHolder,RecyclerView.ViewHolder target) {
Log.e("wds","onMove:"+ viewHolder.getAdapterPosition() +";"+ target.getAdapterPosition());
recyclerView.getAdapter().notifyItemMoved(viewHolder.getAdapterPosition(),target.getAdapterPosition());
return false;
}
@Override
public voidonSwiped(RecyclerView.ViewHolder viewHolder, intdirection) {
Log.e("wds","onSwiped");
}
});
helper.attachToRecyclerView(mDragView);
}
public static classMyAdapterextendsRecyclerView.Adapter {
@Override
publicMyViewHolderonCreateViewHolder(ViewGroup parent, intviewType) {
return newMyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item, null));
}
@Override
public voidonBindViewHolder(MyViewHolder holder, intposition) {
}
@Override
public intgetItemCount() {
return10;
}
}
public static classMyViewHolderextendsRecyclerView.ViewHolder {
public finalImageViewimageView;
publicMyViewHolder(View itemView) {
super(itemView);
imageView= (ImageView) itemView.findViewById(R.id.imageView);
}
}
}
网友评论