После просмотра тонны потоков github и множества-многих веб-сайтов я не нашел никого со своим странным шаблоном, поэтому здесь мы go:
В этот момент при переключении двух элементов, все в порядке, однако, когда я пытаюсь переместить больше, происходит следующее:
Предположим, в вашем адаптере есть порядок ABCDE элементов. Если вы попытаетесь переместить B в последнюю позицию, обновленный заказ будет ACDED, и элемент B будет нигде не найден. Затем, если я закрою приложение и снова открою его, адаптер будет иметь порядок ABCED, почти как оригинал, но не совсем. Если вы решите переместить его в другом направлении, то же самое произойдет в зеркальном отражении. То есть, если вы решите переместить E между A и B, обновленный порядок будет ACBCD, а после повторного открытия ACBDE!
Это очень странный шаблон. Переходим к коду. У меня есть база данных ROOM и стандартный адаптер recyclerview:
Это мой Item Touch Helper:
public class ViewPager_Schedule_Object extends Fragment implements TimePickerDialog.OnTimeSetListener, AlertDialog1.AlertDialog1Listener, AlertDialog2.AlertDialog2Listener {
ViewPager_Schedule_Object() {
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_viewpager_schedule_item, container, false);
Bundle args = getArguments();
daysViewModel = ViewModelProviders.of(this).get(DaysDatabaseViewModel.class);
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("Settings", Context.MODE_PRIVATE);
SharedPreferences.Editor sEditor = sharedPreferences.edit();
RecyclerView recyclerView = root.findViewById(R.id.recyclerview_viewpager_schedule);
daysAdapter = new DaysAdapter();
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(daysAdapter);
daysViewModel.getNotesInDay(args.getInt(ARG_OBJECT)).observe(getViewLifecycleOwner(), new Observer<List<DayActivity>>() {
@Override
public void onChanged(List<DayActivity> dayActivities) {
daysAdapter.submitList(dayActivities);
}
});
ItemTouchHelper mIth = new ItemTouchHelper(
new ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP | ItemTouchHelper.DOWN, 0) {
@Override
public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
final int fromPos = viewHolder.getAdapterPosition();
final int toPos = target.getAdapterPosition();
Log.d("STOP_HERE_please_1", fromPos + " " + toPos);
Bundle arguments = getArguments();
Log.d("STOP_HERE_3", String.valueOf(arguments.getInt(ARG_OBJECT)));
if (fromPos != toPos) {
try2 = new ArrayList<>();
if (fromPos > toPos) {
List<DayActivity> dayActivities = daysAdapter.getOrdersBetween(toPos, fromPos);
for (DayActivity stops :dayActivities) {
if (stops != dayActivities.get(dayActivities.size() - 1)) {
DayActivity new_note = new DayActivity(stops.getTitle_Day(), stops.getLocation_Day(), stops.getStars_Day(),
stops.getOpening_hours_1_Day(), stops.getOpening_hours_2_Day(), stops.getOpening_hours_3_Day(),
stops.getNotas_Day(), stops.getDay_Day(), stops.getStarttime_Day(),
stops.getEndtime_Day(), stops.getOrder_Day() + 1);
new_note.setId_Day(stops.getId_Day());
try2.add(new_note);
} else {
DayActivity new_note = new DayActivity(stops.getTitle_Day(), stops.getLocation_Day(), stops.getStars_Day(),
stops.getOpening_hours_1_Day(), stops.getOpening_hours_2_Day(), stops.getOpening_hours_3_Day(),
stops.getNotas_Day(), stops.getDay_Day(), stops.getStarttime_Day(),
stops.getEndtime_Day(), stops.getOrder_Day() - dayActivities.size() + 1);
new_note.setId_Day(stops.getId_Day());
try2.add(new_note);
}
}
} else {
List<DayActivity> dayActivities = daysAdapter.getOrdersBetween(fromPos, toPos);
Log.d("STOP_HERE_please_3", String.valueOf(dayActivities) + dayActivities.size() + "tambem aqui parou");
for (DayActivity stops :dayActivities) {
if (stops != dayActivities.get(0)) {
DayActivity new_note = new DayActivity(stops.getTitle_Day(), stops.getLocation_Day(), stops.getStars_Day(),
stops.getOpening_hours_1_Day(), stops.getOpening_hours_2_Day(), stops.getOpening_hours_3_Day(),
stops.getNotas_Day(), stops.getDay_Day(), stops.getStarttime_Day(),
stops.getEndtime_Day(), stops.getOrder_Day() - 1);
new_note.setId_Day(stops.getId_Day());
try2.add(new_note);
} else {
DayActivity new_note = new DayActivity(stops.getTitle_Day(), stops.getLocation_Day(), stops.getStars_Day(),
stops.getOpening_hours_1_Day(), stops.getOpening_hours_2_Day(), stops.getOpening_hours_3_Day(),
stops.getNotas_Day(), stops.getDay_Day(), stops.getStarttime_Day(),
stops.getEndtime_Day(), stops.getOrder_Day() + dayActivities.size() - 1);
new_note.setId_Day(stops.getId_Day());
try2.add(new_note);
}
}
}
daysAdapter.onItemMove(fromPos, toPos);
Log.d("STOP_HERE_please_2", "Um breakzinho");
return true;
}
return false;
}
@Override
public boolean isLongPressDragEnabled() {
return true;
}
@Override
public boolean isItemViewSwipeEnabled() {
return false;
}
@Override
public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
}
@Override
public void onSelectedChanged(@Nullable RecyclerView.ViewHolder viewHolder, int actionState) {
super.onSelectedChanged(viewHolder, actionState);
if (actionState == ACTION_STATE_DRAG)
viewHolder.itemView.setAlpha(0.5f);
}
@Override
public void clearView(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
super.clearView(recyclerView, viewHolder);
viewHolder.itemView.setAlpha(1.0f);
if (try2 != null) daysViewModel.updateList(try2);
}
});
mIth.attachToRecyclerView(recyclerView);
return root;
}
Это моя кнопка добавления:
Button button_add_stop = (Button) root.findViewById(R.id.adicionar_paragem_schedule);
button_add_stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Integer shalignement = sharedPreferences.getInt("Number of Order" + args.getInt(ARG_OBJECT), 2) + 1;
sEditor.putInt("Number of Order" + args.getInt(ARG_OBJECT), shalignement);
sEditor.apply();
daysViewModel.insert(new DayActivity(
"", "", (float) -1, "", "", "", "",
args.getInt(ARG_OBJECT), "", "", shalignement
));
recyclerView.smoothScrollBy(0, 5000);
}
});
Это моя кнопка удаления:
daysAdapter.setOnItemClickListener(new DaysAdapter.OnItemClickListener() {
@Override
public void onDeleteClick(DayActivity note, Integer position) {
Log.d("Passagem!", "Vou dar delete");
activeNote = note;
//openDialog2();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Are you Sure?")
.setMessage("There's no coming back!")
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.setPositiveButton("yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Integer shalignement = sharedPreferences.getInt("Number of Order" + args.getInt(ARG_OBJECT), 3);
sEditor.putInt("Number of Order" + args.getInt(ARG_OBJECT), shalignement - 1);
sEditor.apply();
daysViewModel.delete(activeNote);
List<DayActivity> dayActivityList = daysAdapter.getOrdersBetween(position + 1, shalignement);
if (dayActivityList != null) {
for (DayActivity dayActivity :dayActivityList) {
dayActivity.setOrder_Day(dayActivity.getOrder_Day() - 1);
}
}
daysViewModel.updateList(dayActivityList);
daysAdapter.notifyItemRemoved(note.getOrder_Day());
}
});
builder.show();
}
});