Я прочитал много предложений о том, как сохранить текущую позицию прокрутки в RecyclerView
, когда устройство повернуто. Теперь я узнал, что когда я использую com.android.support:recyclerview-v7:23.0.+
, текущая позиция фактически сэкономила в savedInstanceState
. Он также, кажется, восстанавливается, но он восстанавливается «несколько правильно».Сохранять положение прокрутки в RecyclerView
Что я испытываю это: я просматриваю нижнюю часть списка в портретном режиме, затем переключаюсь на пейзаж. Текущая позиция восстановлена правильно (конечно, некоторые элементы не видны - я смогу продолжить прокрутку)!
Без дополнительной прокрутки я поворачиваюсь назад к портрету, и восстановленная позиция находится на несколько позиций выше позиции, которую я бы на самом деле думал. Список больше не прокручивается внизу.
Мой вопрос: есть ли что-нибудь еще, что я могу сделать, чтобы фактически сохранить и восстановить правильную позицию прокрутки?
Это макет для RecyclerView
:
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/swipeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="...">
<android.support.v7.widget.RecyclerView
android:id="@+id/itemsView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
</android.support.v4.widget.SwipeRefreshLayout>
Это укороченный расположение для отдельных элементов:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="8dp"
android:paddingBottom="8dp"
android:paddingLeft="12dp"
android:paddingRight="12dp">
<!-- This linear layout aligns type indicator to the left and text content to the right -->
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
...
</LinearLayout>
</LinearLayout>
фрагмент, который принимает RecyclerView
имеет следующий код:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.calendar_fragment, container, false);
ButterKnife.bind(this, v);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
...
}
});
if (mLayoutManager == null)
{
mLayoutManager = new LinearLayoutManager(getActivity());
mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
}
// Get cached information or access storage
if (savedInstanceState != null)
{
// Initialize the area and the adapter from the saved state
mArea = savedInstanceState.getParcelable("AREA");
Entry[] entries = (Entry[])savedInstanceState.getParcelableArray("ITEMS");
mDataAdapter = new MyAdapter(this, mArea, entries);
}
else
{
// Initialize the area and the adapter form scratch
mArea = getAreaByPreference();
mDataAdapter = new MyAdapter(this, mArea);
}
// Initialize the RecyclerView
mItemsView.setHasFixedSize(true);
mItemsView.setAdapter(mDataAdapter);
mItemsView.setLayoutManager(mLayoutManager);
return v;
}
Вы пытались сохранить позицию, а затем использовать 'void scrollToPosition (int position)'? https://developer.android.com/reference/android/support/v7/widget/LinearLayoutManager.html#scrollToPosition(int) – Jonsmoke
Нет, я еще не пробовал, так как все другие решения, которые я нашел, предложили позволить 'LinearLayoutManager' делать свою вещь, спасая и восстанавливая свое собственное государство. –
Вы видели этот ответ? http://stackoverflow.com/a/29166336/3658819 – Jonsmoke