我有一个RecyclerView – 网格,拖动和使用这个
code我已经设法实现了,并做了很多变化,只有一个问题,我不能保存拖动的项目位置重新启动(应用程序不是手机).
我想到的是在我的item.java构造函数中添加“int position”,但我不能做的就是获得改变的位置.
我想到的是在我的item.java构造函数中添加“int position”,但我不能做的就是获得改变的位置.
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
}
解决方法
只需将修改后的收藏AllItems保存在SharedPreferences中,并将其加载到应用程序开始&一旦您退出应用程序,就将其存储起来.
为此,您需要将您的集合序列化为json,并将其存储为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());