Stop ScrollView from auto-scrolling to an EditText

后端 未结 21 1345
长发绾君心
长发绾君心 2020-11-30 23:17

Seems to be a common problem without a great solution that I have found. Goal is to stop a ScrollView from auto-scrolling to an EditText (or any vi

21条回答
  •  臣服心动
    2020-11-30 23:32

    My solution is below, to trace the source code and override some function to stop auto scrolling by focused item.

    You can check if the focusedView is TextView or its child is TextView, by using focusedView.findViewById(R.id.textview_id_you_defined) != null or focusedView instanceof TextView == true.

    public class StopAutoFocusScrollView extends ScrollView {
    
        private View focusedView;
        private ScrollMonitorListener listener;
    
        public interface ScrollMonitorListener {
            public boolean enableScroll(View view);
        }
        public StopAutoFocusScrollView(Context context) {
            super(context);
        }
    
        public StopAutoFocusScrollView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public StopAutoFocusScrollView(Context context, AttributeSet attrs, 
               int defStyle) {
            super(context, attrs, defStyle);
        }
    
        public void setScrollMonitorListener(ScrollMonitorListener listener) {
            this.listener = listener;
        }
    
        @Override
        public void requestChildFocus(View child, View focused) {
            focusedView = focused
            super.requestChildFocus(child, focused);
        }
        //flow : requestChildFocus -> scrollToChild -> scrollBy
        //Therefore, you can give listener to determine you want scroll to or not
        @Override
        public void scrollBy(int x, int y) {
            if (listener == null || listener.enableScroll(focusedView)) {
                super.scrollBy(x, y);
            }
        }
    }
    

提交回复
热议问题