我在DialogFragment
(确切地说是AlertDialog
)中使用带有拖放功能的RecyclerView
(ItemTouchHelper.Callback
-> onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target)
)。
问题在于,当我上下移动被举起(拖动)的项目时,动画会出现滞后。我尝试使用相同的RecyclerView
在Activity
中的Fragment
中运行,并且运行得很平稳。我怀疑问题在于Activity
占据了整个屏幕,而DialogFragment
没有(模糊的背景显示在对话框周围)。我认为在AlertDialog
中移动项目时进行了一些额外的计算。
编辑过的
我的适配器类:
public class ListAdapter extends RecyclerView.Adapter<ListAdapter.TabItemViewHolder> implements ItemTouchHelperAdapter {
private List<Tab> tabs;
public ListAdapter(List<Tab> tabs) {
this.tabs = tabs;
}
@Override
public TabItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list_tab_list, parent, false);
return new TabItemViewHolder(itemView);
}
@Override
public void onBindViewHolder(TabItemViewHolder holder, final int position) {
Tab tab = tabs.get(position);
holder.tvTabName.setText(tab.getTabCategory().toString());
}
@Override
public int getItemCount() {
return tabs.size();
}
@Override
public void onItemMove(int fromPosition, int toPosition) {
if (fromPosition < toPosition) {
for (int i = fromPosition; i < toPosition; i++) {
Collections.swap(tabs, i, i + 1);
}
} else {
for (int i = fromPosition; i > toPosition; i--) {
Collections.swap(tabs, i, i - 1);
}
}
notifyItemMoved(fromPosition, toPosition);
}
@Override
public void onItemDismiss(int position) {
tabs.remove(position);
notifyItemRemoved(position);
}
public static class TabItemViewHolder extends RecyclerView.ViewHolder {
public TextView tvTabName;
public TabItemViewHolder(final View itemView) {
super(itemView);
tvTabName = (TextView) itemView.findViewById(R.id.cl__tv_tab_name);
}
}
}
函数void onItemMove(int fromPosition, int toPosition)
和void onItemDismiss(int position)
是从ItemTouchHelper
调用的。
DialogFragment
类:
public Dialog onCreateDialog(Bundle savedInstanceState) {
final RecyclerView recyclerView = (RecyclerView) getActivity().getLayoutInflater().inflate(R.layout.recycler_view, null);
ListAdapter listAdapter = new ListAdapter (tabs);
recyclerView.setAdapter(listAdapter );
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
SimpleItemTouchHelperCallback simpleItemTouchHelperCallback = new SimpleItemTouchHelperCallback(listAdapter);
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleItemTouchHelperCallback);
itemTouchHelper.attachToRecyclerView(recyclerView);
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.title)
.setView(recyclerView)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).create();
}