我正在使用simpleItemTouchHelper在recyclelerview中启用拖放功能。它运行良好。但我想通过拖动一个项目来拖动多个项目(具体数量 - > 3或4)。在我的项目中,当我选择时并拖动标题项,我也想移动其他子项。我该怎么做?
这是我的代码:
活动
public class TestActivity extends AppCompatActivity implements OnStartDragListener {
RecyclerView recyclerView;
private ItemTouchHelper mItemTouchHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
TestAdapter adapter = new TestAdapter(this,getDatas(),this);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
ItemTouchHelper.Callback callback = new SimpleItemTouchHelper(adapter);
mItemTouchHelper = new ItemTouchHelper(callback);
mItemTouchHelper.attachToRecyclerView(recyclerView);
}
private List<Integer> getDatas(){
return new ArrayList<>(Arrays.asList(
0,
1,
1,
1,
0,
1,
1,
1,
0,
1,
1,
1
));
}
@Override
public void onStartDrag(RecyclerView.ViewHolder viewHolder) {
mItemTouchHelper.startDrag(viewHolder);
}
}
适配器:
public class TestAdapter extends RecyclerView.Adapter<TestAdapter.ItemViewHolder>
implements ItemTouchHelperAdapter {
private Context context;
private List<Integer> lists;
private OnStartDragListener onStartDragListener;
public TestAdapter(Context context, List<Integer> lists,OnStartDragListener onStartDragListener) {
this.context = context;
this.lists = lists;
this.onStartDragListener = onStartDragListener;
}
@Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = null;
if(viewType == 0){
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_header,parent,false);
}else if(viewType == 1){
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_child,parent,false);
}
return new ItemViewHolder(view);
}
@Override
public int getItemViewType(int position) {
return lists.get(position);
}
@Override
public void onBindViewHolder(final ItemViewHolder holder, int position) {
holder.itemView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (MotionEventCompat.getActionMasked(event) == event.ACTION_DOWN) {
onStartDragListener.onStartDrag(holder);
}
return true;
}
});
}
@Override
public int getItemCount() {
return lists.size();
}
@Override
public boolean onItemMove(int fromPosition, int toPosition) {
if (fromPosition < toPosition) {
for (int i = fromPosition; i < toPosition; i++) {
Collections.swap(lists, i, i + 1);
}
} else {
for (int i = fromPosition; i > toPosition; i--) {
Collections.swap(lists, i, i - 1);
}
}
notifyItemMoved(fromPosition, toPosition);
return true;
}
public class ItemViewHolder extends RecyclerView.ViewHolder{
public ItemViewHolder(View itemView) {
super(itemView);
}
}
}
听众在这里:
public interface OnStartDragListener {
void onStartDrag(RecyclerView.ViewHolder viewHolder);
}
public interface ItemTouchHelperAdapter {
boolean onItemMove(int fromPosition, int toPosition);
}