我有一个 RecyclerView - 网格,可以拖放,使用这个 code我已经设法实现了这一点,并进行了很多更改,只有一个问题,我无法在重新启动时保存拖动项目的位置(应用程序而不是手机)。 我想到的是将“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);
}
获取所有项目列表:
private List<Item> getAllItemList(){
AllItems = SharedPreferencesTools.getOrderedItems(this);
//Add item .. etc
//return items
最佳答案
只需将修改后的集合 AllItems
保存在 SharedPreferences
中,并在应用程序启动时加载它,并在您退出应用程序后将其存储回来。
为此,您需要通过 Gson
将您的集合序列化为 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());
关于android - 重新启动时保持拖放项目的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35037487/