我想在Android上创建带动画的排序。
我认为最好的方法是使用RecyclerView
。
为了获得更好的用户体验,我想展示一些动画,尤其是当RecyclerView
我认为有两种类型的动画可以做。
1交换项目,例如冒泡
2个移位项目,例如插入排序
答案 0 :(得分:2)
以下是您想要的示例代码。
在您的片段或活动中。
MyAdapter adapter = new MyAdapter(getActivity(), mDataSet);
ItemTouchHelper.Callback callback = new RecyclerItemTouchHelper(adapter);
ItemTouchHelper helper = new ItemTouchHelper(callback);
helper.attachToRecyclerView(mRecyclerView);
//Here mRecyclerView is ref of your RecyclerView & mDataSet is List of your data set.
然后是适配器的代码。
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private Context mContext;
private List<Object> mDataSet = new ArrayList<>();
//Replace Object with your data type
public MyAdapter(Context context, List<Object> dataSet) {
mContext = context;
mDataSet=dataSet;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_layout, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Object object = mDataSet.get(position);
//Do your Stuff
}
public void onMove(RecyclerView recyclerView, int firstPos, int secondPos) {
/*Do your stuff what you want
Notify your adapter about change in positions using notifyItemMoved method
Shift element e.g. insertion sort*/
}
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
/*Do your stuff what you want
Swap element e.g. bubbleSort*/
}
@Override
public int getItemCount() {
return mDataSet.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
CardView mCardView;
public ViewHolder(View itemView) {
super(itemView);
mCardView = (CardView) itemView.findViewById(R.id.card_view);
}
}
}
以下是 RecyclerItemTouchHelper 的代码。
public class RecyclerItemTouchHelper extends ItemTouchHelper.SimpleCallback {
private MyAdapter mAdapter;
public RecyclerItemTouchHelper(SmartSocketAdapter adapter){
super(ItemTouchHelper.UP | ItemTouchHelper.DOWN, 0);
mAdapter = adapter;
}
@Override
public boolean onMove(final RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
mAdapter.onMove(recyclerView,viewHolder.getAdapterPosition(), target.getAdapterPosition());
return true;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
mAdapter.onSwiped(viewHolder, direction);
}
}
通过这种方式,您可以在适配器中获得两个回调,您可以通过适配器通知适配器,也可以使用notifyItemMoved方法获得动画。