現象:當一個scrollView 里面包含很多childView,並且整個界面超出屏幕的范圍,而且每個childView都獲取焦點,scrollView就會自動滑到底部或者中間部分。
可以使用以下幾種方法解決:
1:有點繞,基本思路,就是讓scrollView優先於childView獲取到焦點, private void disableAutoScrollToBottom() { mScrollView.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS); mScrollView.setFocusable(true); mScrollView.setFocusableInTouchMode(true); mScrollView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { v.requestFocusFromTouch(); return false; } }); } 恢復默認狀態,禁掉scrollview的focus,這樣就允許childview自動滑動 private void enableChildAutoScrollToBottom() { mScrollView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS); mScrollView.setFocusable(false); mScrollView.setFocusableInTouchMode(false); mScrollView.setOnTouchListener(null); }
方法二: 將可能自動滑動的childview的focus禁掉,防止它自動滑動 mContentTextBox.setFocusable(false); 恢復默認狀態,允許childview的focus,使它可以自動滑動 mContentTextBox.setFocusableInTouchMode(true); mContentTextBox.setFocusable(true); 這里要注意,僅僅setFocusable為true是不夠的,需要設setFocusableInTouchMode。
方法三:重寫ScrollView的方法 @Override protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) { return 0; } 或者 @Override protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) { return true; }
