当我返回Fragment时,我有2个可重用的方法来恢复y RecyclerView中项目的位置。它适用于我的其他碎片。但是我有一个带有灵活空间的片段,图像为scrolling-techniques-behavior,在NestedScrollView中有一个RecyclerView。我无法获得位置和偏移量。我可以从适配器获得位置。但是当我尝试恢复位置时,没有任何反应,它总是显示顶部项目。
public static void storeRecyclerViewListPosition(Activity activity, final RecyclerView recyclerView, String identifier) {
Log.i(TAG, "storeRecyclerViewListPosition: " + identifier);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
View firstChild = recyclerView.getChildAt(0);
if (firstChild != null) {
int firstVisiblePosition = recyclerView.getChildAdapterPosition(firstChild);
int offset = firstChild.getTop();
Log.d(TAG, "storeRecyclerViewListPosition: " + identifier + "_position: " + firstVisiblePosition);
Log.d(TAG, "storeRecyclerViewListPosition: " + identifier + "_offset: " + offset);
preferences.edit()
.putInt(identifier + "_position", firstVisiblePosition)
.putInt(identifier + "_offset", offset)
.apply();
}
}
public static void restoreRecyclerViewListPosition(Activity activity, final RecyclerView recyclerView, final String identifier) {
Log.i(TAG, "restoreRecyclerViewListPosition: " + identifier);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
Log.d(TAG, "storeRecyclerViewListPosition: " + identifier + "_position: " + preferences.getInt(identifier + "_position", 0));
Log.d(TAG, "storeRecyclerViewListPosition: " + identifier + "_offset: " + preferences.getInt(identifier + "_offset", 0));
recyclerView.scrollToPosition(preferences.getInt(identifier + "_position", 0));
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
recyclerView.scrollBy(0, - preferences.getInt(identifier + "_offset", 0));
}
}, 500);
}
答案 0 :(得分:0)
你在做什么基本上是这样的:
int firstVisiblePosition = recyclerView.getChildAdapterPosition(recyclerView.getChildAt(0));
如标题所示,这与此相同:
int firstVisiblePosition = 0;
相反,你应该这样做:
int firstVisiblePosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstCompletelyVisibleItemPosition();
也适用于GridLayoutManager
。
我相应地采用了你的方法并对它们进行了一些编辑。这对我有用:
@Override
protected void onPause() {
storeRecyclerViewListPosition();
super.onPause();
}
@Override
protected void onResume() {
restoreRecyclerViewListPosition();
super.onResume();
}
public void storeRecyclerViewListPosition() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
int firstVisiblePosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
preferences.edit().putInt("position", firstVisiblePosition).apply();
}
public void restoreRecyclerViewListPosition() {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
recyclerView.smoothScrollToPosition(preferences.getInt("position", 0));
}