Android cardview通过拖放更改位置

时间:2017-05-04 16:27:26

标签: java android android-cardview cardview

我想在片段(导航抽屉)中制作我的卡片视图,能够通过拖放更改列表中的位置。

我的布局文件结构:

FrameLayout{
LinearLayout{
cardview_1
card_view_2}}

1 个答案:

答案 0 :(得分:2)

使用recyclerView并使用cardView作为root View创建rowItemLayout.xml或columnItemLayout.xml。 然后使用recyclerView的功能,例如:

ItemTouchHelper itemTouchHelper = new ItemTouchHelper(createHelperCallback());
itemTouchHelper.attachToRecyclerView(recyclerView);
private ItemTouchHelper.Callback createHelperCallback() {
    ItemTouchHelper.SimpleCallback simpleItemTouchCallback =
            new ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP | ItemTouchHelper.DOWN,
                    ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
                @Override
                public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder,
                                      RecyclerView.ViewHolder target) {
                    moveItem(viewHolder.getAdapterPosition(), target.getAdapterPosition());
                    return true;
                }

                @Override
                public void onSwiped(final RecyclerView.ViewHolder viewHolder, int swipeDir) {
                    deleteItem(viewHolder.getAdapterPosition());
                }
            };
    return simpleItemTouchCallback;
}
 private void moveItem(int oldPos, int newPos) {

    ListItem item = (ListItem) listData.get(oldPos);
    listData.remove(oldPos);
    listData.add(newPos, item);
    adapter.notifyItemMoved(oldPos, newPos);
}

private void deleteItem(final int position) {
    listData.remove(position);
    adapter.notifyItemRemoved(position);
}