Stop ScrollView from auto-scrolling to an EditText

后端 未结 21 1351
长发绾君心
长发绾君心 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:37

    After struggling with that problem for quite some time, I've found a solution that seems to work without being too ugly. First, make sure that whatever ViewGroup (directly) contains your EditText has descendantFocusability set to "Before Descendants," focusable set to "true" and focusableInTouchMode set to "true." This will not be the ScrollView itself, but the layout inside where you have your various views. Next add an onTouchListener to your ScrollView that removes focus from the EditText whenever it is touched, like so:

    ScrollView scroll = (ScrollView)findViewById(R.id.scrollView1);
    scroll.setOnTouchListener(new OnTouchListener() {
    
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (myEditText.hasFocus()) {
                myEditText.clearFocus();
            }
            return false;
        }
    });
    

    Tell me if that doesn't fix it. What should happen is that the Layout gets focus instead of the EditText, so no scrolling should happen.

提交回复
热议问题