重新启动时保持拖放项目的位置

我有一个RecyclerView – 网格,用拖放,使用这个代码,我已经设法实现了,做了很多改变,只有一个问题,我不能保存拖动项目的位置重新启动(应用程序不是电话 )。 我想到的是将“int position”添加到我的item.java构造函数中,但是我不能做的是获取更改后的位置。

我使用链接中提供的相同的拖放代码。

ItemTouchHelper.Callback _ithCallback = new ItemTouchHelper.Callback() { //and in your imlpementaion of public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { // get the viewHolder's and target's positions in your adapter data, swap them Collections.swap(AllItems, viewHolder.getAdapterPosition(), target.getAdapterPosition()); // and notify the adapter that its dataset has changed rcAdapter.notifyItemMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition()); return true; } @Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) { //TODO } //defines the enabled move directions in each state (idle, swiping, dragging). @Override public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { return makeFlag(ItemTouchHelper.ACTION_STATE_DRAG, ItemTouchHelper.DOWN | ItemTouchHelper.UP | ItemTouchHelper.START | ItemTouchHelper.END); } }; 

以下是onCreate中的代码:

  ItemTouchHelper ith = new ItemTouchHelper(_ithCallback); ith.attachToRecyclerView(RcView); 

位置改变后获取重复项目,代码:

  @Override public void onStop() { super.onStop(); SharedPreferencesTools.setOrderedItems(this, AllItems); } 

getAllItemList:

 private List<Item> getAllItemList(){ AllItems = SharedPreferencesTools.getOrderedItems(this); //Add item .. etc //return items 

}

Solutions Collecting From Web of "重新启动时保持拖放项目的位置"

只要将您的修改后的集合AllItemsSharedPreferences并将其加载到应用程序中即可。

要做到这一点,你需要将你的集合序列化到json的Gson并以String存储。 然后将其反序列化:

 public final class SharedPreferencesTools { private static final String USER_SETTINGS_PREFERENCES_NAME = "UserSettings"; private static final String ALL_ITEMS_LIST = "AllItemsList"; private static Gson gson = new GsonBuilder().create(); public static List<Item> getOrderedItems(Context context) { String stringValue = getUserSettings(context).getString(ALL_ITEMS_LIST, ""); Type collectionType = new TypeToken<List<Item>>() { }.getType(); List<Item> result = gson.fromJson(stringValue, collectionType); return (result == null) ? new ArrayList<Item>() : result; } public static void setOrderedItems(Context context, List<Item> items) { String stringValue = gson.toJson(items); SharedPreferences sharedPreferences = getUserSettings(context); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(ALL_ITEMS_LIST, stringValue); editor.apply(); } static SharedPreferences getUserSettings(Context context) { return context.getSharedPreferences(USER_SETTINGS_PREFERENCES_NAME, Context.MODE_PRIVATE); } } 

这两种方法的用法:

  SharedPreferencesTools.setOrderedItems(getActivity(), AllItems); ... List<Item> AllItems = SharedPreferencesTools.getOrderedItems(getActivity());