界面为ScrollView时打开界面会自动滚动到底部之解决方法

时间:2023-03-10 01:23:16
界面为ScrollView时打开界面会自动滚动到底部之解决方法

开发中遇到了这样的一个问题,界面最外层是ScrollView,然后里面有嵌套了一个ListView还有其他可以获取焦点的View,然后每次打开界面都会自动滚动到最底部,经过一番折腾,发现了一个简单的方法,

获取ScrollView里面一个上层任意view,然后调用如下方法:

view.setFocusable(true);
view.setFocusableInTouchMode(true);
view.requestFocus();


或者将scrollview包裹的内容设置上以下两个属性

android:focusable="true"

android:focusableInTouchMode="true"

<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="none"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical"
android:focusable="true"
android:focusableInTouchMode="true" />
</ScrollView