这是我的布局:
当屏幕方向改变时,我需要保存滚动位置。例如,如果在竖屏模式下屏幕显示从中间名称开始的布局,则在横屏模式下也应该从同一位置开始。
这是我的布局:
当屏幕方向改变时,我需要保存滚动位置。例如,如果在竖屏模式下屏幕显示从中间名称开始的布局,则在横屏模式下也应该从同一位置开始。
只需在您的滚动元素上设置android:id。您的视图将自动保存其滚动位置。
来自View.java的代码:15554
protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
Parcelable state = onSaveInstanceState();
if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
throw new IllegalStateException(
"Derived class did not call super.onSaveInstanceState()");
}
if (state != null) {
// Log.i("View", "Freezing #" + Integer.toHexString(mID)
// + ": " + state);
container.put(mID, state);
}
}
}
当手机方向改变时,保存和恢复ScrollView的滚动位置可以按照以下步骤进行: 在onSaveInstanceState方法中保存当前位置:
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putIntArray("ARTICLE_SCROLL_POSITION",
new int[]{ mScrollView.getScrollX(), mScrollView.getScrollY()});
}
然后在onRestoreInstanceState方法中恢复位置。需要注意的是,我们需要向ScrollView发布一个Runnable才能使其正常工作:
然后在onRestoreInstanceState
方法中恢复位置。需要注意的是,我们需要向ScrollView
发送一个Runnable
以使其正常工作:
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
final int[] position = savedInstanceState.getIntArray("ARTICLE_SCROLL_POSITION");
if(position != null)
mScrollView.post(new Runnable() {
public void run() {
mScrollView.scrollTo(position[0], position[1]);
}
});
}
在谷歌上找到了这个解决方案。鸣谢原作者。:)
mScrollView.scrollTo(position[0], position[1] + getScreenWidth()/4);
- the_proleprotected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/search_text"
android:maxLines="1"
android:inputType="text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Enter search string here" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="doSearch"
android:clickable="true"
android:text="Search"
android:layout_toRightOf="@id/search_text"/>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/list_of_books"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/search_text"
android:divider="@null"
android:orientation="vertical" />
</RelativeLayout>
在清单文件中执行此操作...
<activity
android:name=".YourActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/app_name" >
</activity>
NestedScrollView
中使用RecyclerView
时,这并没有对我起作用,但是下面Umesh Clauhan的解决方案有效。 - Minas Mina