上一篇文章剛講到使用scrollview嵌套listview或gridview來使用出現只顯示一個item高度的問題的解決方法。重寫他的測量方法,本篇我就不多提了。
使用了嵌套的小夥伴們會發現一個問題,那就是每次進來之後scrollview自動滾動到了和listview的頂部對齊的狀態。
佈局代碼
> LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ScrollView
android:id="@+id/sv"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#ff0000"
android:gravity="center"
android:text="數據展示" />
<com.zongke.weiduo.view.MyListview
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</ScrollView>
</LinearLayout>
每次進來界面之後就會發現每次scrollview將自動滾動到listview的第一條數據處,這和我們的預期效果是不一樣的。我們要的效果是每次進來就讓scrollview滾動到最頂部。那怎麼樣達成這個效果呢?
大家可能第一時間想到的是在進入該界面時調用scrollview的scrollTo(0,0)這個方法,大家試試會發現是無效的。
下面我給大家介紹一下兩種方法,
1.加載界面時強行把焦點聚焦在listview上面的控件上:(這個方法也是我在網上看的大家用的比較多的方法)
比如這個例子
只需要得到listview上面的控件,強行讓改控件獲取到焦點,就能讓scrollview每次自動滑動到最頂部。
tv = (TextView) findViewById(R.id.tv);
tv.findFocus();
tv.setFocusable(true);
tv.setFocusableInTouchMode(true);
2.只需要調用scrollview的立即滾動的方法:
比如這個例子
只需得到scrollview調用它的smoothScrollTo();方法把座標設置爲最頂部。
sv = (ScrollView) findViewById(R.id.sv);
sv.smoothScrollTo(0,0);
總結:
這兩種方式都能解決scrollview嵌套listview後出現scrollview亂滾動的問題。大家可以想象一個場景,當用戶滑動到listview的中間部分時,突然退出該界面,在進來scrollview又滑動到了最頂部,那將是一個很不好的用戶體驗,當然也可以在判斷用戶是否爲第一次進入該界面,在離開的時候保存座標,在次進來時,把座標拿到給scrollview設置。但是個人還是更偏向推薦第二種方式。
個人經驗分享,如有錯誤或疑問,給我留言探討。